prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  ProgressBar extension doesn't show correct `iters/sec` in ppe==0.5.0
  The `ProgressBar` extension shows `iters/sec` as well as the progress bar, but I noticed that in ppe==0.5.0 it becomes always `inf iters/sec`.
  
  ### ppe==0.5.0
  
  Minimum reproduction code:
  ```python
  # progress.py (based on https://git.io/JzHP3)
  import pytorch_pfn_extras as ppe
  import time
  
  print("PPE =", ppe.__version__)
  
  max_epochs = 3
  iters_per_epoch = 20
  manager = ppe.training.ExtensionsManager({}, {}, max_epochs, iters_per_epoch=iters_per_epoch)
  manager.extend(ppe.training.extensions.ProgressBar(training_length=None, update_interval=1, bar_length=40))
  
  for epoch in range(max_epochs):
      for _ in range(iters_per_epoch):
          with manager.run_iteration():
              pass
          time.sleep(0.1)
  ```
  
  Result:
  ```
  $ python progress.py
  PPE = 0.5.0
       total [####################....................] 51.67%
  this epoch [######################..................] 55.00%
          31 iter, 1 epoch / 3 epochs
         inf iters/sec. Estimated time to finish: 0:00:00.
  ```
  
  ### ppe==0.4.5 (expected behavior)
  It shows a correct iters/sec.
  ```
  $ python progress.py
  PPE = 0.4.5
       total [#################.......................] 43.33%
  this epoch [############............................] 30.00%
          26 iter, 1 epoch / 3 epochs
      10.825 iters/sec. Estimated time to finish: 0:00:03.140780.
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `pytorch_pfn_extras/training/extensions/util.py`
  Content:
  ```
  1 import os
  2 import sys
  3 import queue
  4 import time
  5 from typing import NamedTuple, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING
  6 
  7 if TYPE_CHECKING:
  8     from pytorch_pfn_extras.training.manager import _BaseExtensionsManager
  9 
  10 
  11 if os.name == 'nt':
  12     import ctypes
  13     from ctypes import windll  # type: ignore [attr-defined]
  14 
  15     _STD_OUTPUT_HANDLE = -11
  16 
  17     _COORD = ctypes.wintypes._COORD
  18 
  19     class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
  20         _fields_ = [('dwSize', _COORD), ('dwCursorPosition', _COORD),
  21                     ('wAttributes', ctypes.c_ushort),
  22                     ('srWindow', ctypes.wintypes.SMALL_RECT),
  23                     ('dwMaximumWindowSize', _COORD)]
  24 
  25     def set_console_cursor_position(x: int, y: int) -> None:
  26         """Set relative cursor position from current position to (x,y)"""
  27 
  28         whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)
  29         csbi = _CONSOLE_SCREEN_BUFFER_INFO()
  30         windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))
  31         cur_pos = csbi.dwCursorPosition
  32         pos = _COORD(cur_pos.X + x, cur_pos.Y + y)
  33 
  34         # Workaround the issue that pyreadline overwrites the argtype
  35         setpos = windll.kernel32.SetConsoleCursorPosition
  36         argtypes = setpos.argtypes
  37         setpos.argtypes = None
  38         setpos(whnd, pos)
  39         setpos.argtypes = argtypes
  40 
  41     def erase_console(x: int, y: int, mode: int = 0) -> None:
  42         """Erase screen.
  43 
  44         Mode=0: From (x,y) position down to the bottom of the screen.
  45         Mode=1: From (x,y) position down to the beginning of line.
  46         Mode=2: Hole screen
  47         """
  48 
  49         whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)
  50         csbi = _CONSOLE_SCREEN_BUFFER_INFO()
  51         windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))
  52         cur_pos = csbi.dwCursorPosition
  53         wr = ctypes.c_ulong()
  54         if mode == 0:
  55             num = csbi.srWindow.Right * (
  56                 csbi.srWindow.Bottom - cur_pos.Y) - cur_pos.X
  57             windll.kernel32.FillConsoleOutputCharacterA(
  58                 whnd, ord(' '), num, cur_pos, ctypes.byref(wr))
  59         elif mode == 1:
  60             num = cur_pos.X
  61             windll.kernel32.FillConsoleOutputCharacterA(
  62                 whnd, ord(' '), num, _COORD(0, cur_pos.Y), ctypes.byref(wr))
  63         elif mode == 2:
  64             os.system('cls')
  65 
  66 
  67 class _QueUnit(NamedTuple):
  68     iteration: int
  69     epoch_detail: float
  70     time: float
  71 
  72 
  73 class ProgressBar:
  74 
  75     def __init__(self, out: Optional[TextIO] = None) -> None:
  76         self._out = sys.stdout if out is None else out
  77         self._recent_timing: 'queue.Queue[_QueUnit]' = queue.Queue(maxsize=100)
  78 
  79     def update_speed(
  80             self,
  81             iteration: int,
  82             epoch_detail: float
  83     ) -> Tuple[float, float]:
  84         now = time.time()
  85         self._recent_timing.put(_QueUnit(iteration, epoch_detail, now))
  86         old = self._recent_timing.get()
  87         span = now - old.time
  88         if span != 0:
  89             speed_t = (iteration - old.iteration) / span
  90             speed_e = (epoch_detail - old.epoch_detail) / span
  91         else:
  92             speed_t = float('inf')
  93             speed_e = float('inf')
  94         return speed_t, speed_e
  95 
  96     def get_lines(self) -> Sequence[str]:
  97         raise NotImplementedError
  98 
  99     def update(
  100             self,
  101             manager: Optional['_BaseExtensionsManager'] = None
  102     ) -> None:
  103         self.erase_console()
  104 
  105         lines = self.get_lines()
  106         for line in lines:
  107             self._out.write(line)
  108 
  109         self.move_cursor_up(len(lines))
  110         self.flush()
  111 
  112     def close(self) -> None:
  113         self.erase_console()
  114         self.flush()
  115 
  116     def erase_console(self) -> None:
  117         if os.name == 'nt':
  118             erase_console(0, 0)
  119         else:
  120             self._out.write('\033[J')
  121 
  122     def move_cursor_up(self, n: int) -> None:
  123         # move the cursor to the head of the progress bar
  124         if os.name == 'nt':
  125             set_console_cursor_position(0, - n)
  126         else:
  127             self._out.write('\033[{:d}A'.format(n))
  128 
  129     def flush(self) -> None:
  130         if hasattr(self._out, 'flush'):
  131             self._out.flush()
  132
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/pytorch_pfn_extras/training/extensions/util.py b/pytorch_pfn_extras/training/extensions/util.py
  --- a/pytorch_pfn_extras/training/extensions/util.py
  +++ b/pytorch_pfn_extras/training/extensions/util.py
  @@ -1,8 +1,8 @@
  +import collections
   import os
   import sys
  -import queue
   import time
  -from typing import NamedTuple, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING
  +from typing import Deque, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING
   
   if TYPE_CHECKING:
       from pytorch_pfn_extras.training.manager import _BaseExtensionsManager
  @@ -64,17 +64,12 @@
               os.system('cls')
   
   
  -class _QueUnit(NamedTuple):
  -    iteration: int
  -    epoch_detail: float
  -    time: float
  -
  -
   class ProgressBar:
   
       def __init__(self, out: Optional[TextIO] = None) -> None:
           self._out = sys.stdout if out is None else out
  -        self._recent_timing: 'queue.Queue[_QueUnit]' = queue.Queue(maxsize=100)
  +        self._recent_timing: Deque[Tuple[int, float, float]] = collections.deque(
  +            [], maxlen=100)
   
       def update_speed(
               self,
  @@ -82,12 +77,12 @@
               epoch_detail: float
       ) -> Tuple[float, float]:
           now = time.time()
  -        self._recent_timing.put(_QueUnit(iteration, epoch_detail, now))
  -        old = self._recent_timing.get()
  -        span = now - old.time
  +        self._recent_timing.append((iteration, epoch_detail, now))
  +        old_t, old_e, old_sec = self._recent_timing[0]
  +        span = now - old_sec
           if span != 0:
  -            speed_t = (iteration - old.iteration) / span
  -            speed_e = (epoch_detail - old.epoch_detail) / span
  +            speed_t = (iteration - old_t) / span
  +            speed_e = (epoch_detail - old_e) / span
           else:
               speed_t = float('inf')
               speed_e = float('inf')
  
verification_info: {"golden_diff": "diff --git a/pytorch_pfn_extras/training/extensions/util.py b/pytorch_pfn_extras/training/extensions/util.py\n--- a/pytorch_pfn_extras/training/extensions/util.py\n+++ b/pytorch_pfn_extras/training/extensions/util.py\n@@ -1,8 +1,8 @@\n+import collections\n import os\n import sys\n-import queue\n import time\n-from typing import NamedTuple, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING\n+from typing import Deque, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING\n \n if TYPE_CHECKING:\n     from pytorch_pfn_extras.training.manager import _BaseExtensionsManager\n@@ -64,17 +64,12 @@\n             os.system('cls')\n \n \n-class _QueUnit(NamedTuple):\n-    iteration: int\n-    epoch_detail: float\n-    time: float\n-\n-\n class ProgressBar:\n \n     def __init__(self, out: Optional[TextIO] = None) -> None:\n         self._out = sys.stdout if out is None else out\n-        self._recent_timing: 'queue.Queue[_QueUnit]' = queue.Queue(maxsize=100)\n+        self._recent_timing: Deque[Tuple[int, float, float]] = collections.deque(\n+            [], maxlen=100)\n \n     def update_speed(\n             self,\n@@ -82,12 +77,12 @@\n             epoch_detail: float\n     ) -> Tuple[float, float]:\n         now = time.time()\n-        self._recent_timing.put(_QueUnit(iteration, epoch_detail, now))\n-        old = self._recent_timing.get()\n-        span = now - old.time\n+        self._recent_timing.append((iteration, epoch_detail, now))\n+        old_t, old_e, old_sec = self._recent_timing[0]\n+        span = now - old_sec\n         if span != 0:\n-            speed_t = (iteration - old.iteration) / span\n-            speed_e = (epoch_detail - old.epoch_detail) / span\n+            speed_t = (iteration - old_t) / span\n+            speed_e = (epoch_detail - old_e) / span\n         else:\n             speed_t = float('inf')\n             speed_e = float('inf')\n", "issue": "ProgressBar extension doesn't show correct `iters/sec` in ppe==0.5.0\nThe `ProgressBar` extension shows `iters/sec` as well as the progress bar, but I noticed that in ppe==0.5.0 it becomes always `inf iters/sec`.\r\n\r\n### ppe==0.5.0\r\n\r\nMinimum reproduction code:\r\n```python\r\n# progress.py (based on https://git.io/JzHP3)\r\nimport pytorch_pfn_extras as ppe\r\nimport time\r\n\r\nprint(\"PPE =\", ppe.__version__)\r\n\r\nmax_epochs = 3\r\niters_per_epoch = 20\r\nmanager = ppe.training.ExtensionsManager({}, {}, max_epochs, iters_per_epoch=iters_per_epoch)\r\nmanager.extend(ppe.training.extensions.ProgressBar(training_length=None, update_interval=1, bar_length=40))\r\n\r\nfor epoch in range(max_epochs):\r\n    for _ in range(iters_per_epoch):\r\n        with manager.run_iteration():\r\n            pass\r\n        time.sleep(0.1)\r\n```\r\n\r\nResult:\r\n```\r\n$ python progress.py\r\nPPE = 0.5.0\r\n     total [####################....................] 51.67%\r\nthis epoch [######################..................] 55.00%\r\n        31 iter, 1 epoch / 3 epochs\r\n       inf iters/sec. Estimated time to finish: 0:00:00.\r\n```\r\n\r\n### ppe==0.4.5 (expected behavior)\r\nIt shows a correct iters/sec.\r\n```\r\n$ python progress.py\r\nPPE = 0.4.5\r\n     total [#################.......................] 43.33%\r\nthis epoch [############............................] 30.00%\r\n        26 iter, 1 epoch / 3 epochs\r\n    10.825 iters/sec. Estimated time to finish: 0:00:03.140780.\r\n```\n", "before_files": [{"content": "import os\nimport sys\nimport queue\nimport time\nfrom typing import NamedTuple, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from pytorch_pfn_extras.training.manager import _BaseExtensionsManager\n\n\nif os.name == 'nt':\n    import ctypes\n    from ctypes import windll  # type: ignore [attr-defined]\n\n    _STD_OUTPUT_HANDLE = -11\n\n    _COORD = ctypes.wintypes._COORD\n\n    class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):\n        _fields_ = [('dwSize', _COORD), ('dwCursorPosition', _COORD),\n                    ('wAttributes', ctypes.c_ushort),\n                    ('srWindow', ctypes.wintypes.SMALL_RECT),\n                    ('dwMaximumWindowSize', _COORD)]\n\n    def set_console_cursor_position(x: int, y: int) -> None:\n        \"\"\"Set relative cursor position from current position to (x,y)\"\"\"\n\n        whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)\n        csbi = _CONSOLE_SCREEN_BUFFER_INFO()\n        windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))\n        cur_pos = csbi.dwCursorPosition\n        pos = _COORD(cur_pos.X + x, cur_pos.Y + y)\n\n        # Workaround the issue that pyreadline overwrites the argtype\n        setpos = windll.kernel32.SetConsoleCursorPosition\n        argtypes = setpos.argtypes\n        setpos.argtypes = None\n        setpos(whnd, pos)\n        setpos.argtypes = argtypes\n\n    def erase_console(x: int, y: int, mode: int = 0) -> None:\n        \"\"\"Erase screen.\n\n        Mode=0: From (x,y) position down to the bottom of the screen.\n        Mode=1: From (x,y) position down to the beginning of line.\n        Mode=2: Hole screen\n        \"\"\"\n\n        whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)\n        csbi = _CONSOLE_SCREEN_BUFFER_INFO()\n        windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))\n        cur_pos = csbi.dwCursorPosition\n        wr = ctypes.c_ulong()\n        if mode == 0:\n            num = csbi.srWindow.Right * (\n                csbi.srWindow.Bottom - cur_pos.Y) - cur_pos.X\n            windll.kernel32.FillConsoleOutputCharacterA(\n                whnd, ord(' '), num, cur_pos, ctypes.byref(wr))\n        elif mode == 1:\n            num = cur_pos.X\n            windll.kernel32.FillConsoleOutputCharacterA(\n                whnd, ord(' '), num, _COORD(0, cur_pos.Y), ctypes.byref(wr))\n        elif mode == 2:\n            os.system('cls')\n\n\nclass _QueUnit(NamedTuple):\n    iteration: int\n    epoch_detail: float\n    time: float\n\n\nclass ProgressBar:\n\n    def __init__(self, out: Optional[TextIO] = None) -> None:\n        self._out = sys.stdout if out is None else out\n        self._recent_timing: 'queue.Queue[_QueUnit]' = queue.Queue(maxsize=100)\n\n    def update_speed(\n            self,\n            iteration: int,\n            epoch_detail: float\n    ) -> Tuple[float, float]:\n        now = time.time()\n        self._recent_timing.put(_QueUnit(iteration, epoch_detail, now))\n        old = self._recent_timing.get()\n        span = now - old.time\n        if span != 0:\n            speed_t = (iteration - old.iteration) / span\n            speed_e = (epoch_detail - old.epoch_detail) / span\n        else:\n            speed_t = float('inf')\n            speed_e = float('inf')\n        return speed_t, speed_e\n\n    def get_lines(self) -> Sequence[str]:\n        raise NotImplementedError\n\n    def update(\n            self,\n            manager: Optional['_BaseExtensionsManager'] = None\n    ) -> None:\n        self.erase_console()\n\n        lines = self.get_lines()\n        for line in lines:\n            self._out.write(line)\n\n        self.move_cursor_up(len(lines))\n        self.flush()\n\n    def close(self) -> None:\n        self.erase_console()\n        self.flush()\n\n    def erase_console(self) -> None:\n        if os.name == 'nt':\n            erase_console(0, 0)\n        else:\n            self._out.write('\\033[J')\n\n    def move_cursor_up(self, n: int) -> None:\n        # move the cursor to the head of the progress bar\n        if os.name == 'nt':\n            set_console_cursor_position(0, - n)\n        else:\n            self._out.write('\\033[{:d}A'.format(n))\n\n    def flush(self) -> None:\n        if hasattr(self._out, 'flush'):\n            self._out.flush()\n", "path": "pytorch_pfn_extras/training/extensions/util.py"}], "after_files": [{"content": "import collections\nimport os\nimport sys\nimport time\nfrom typing import Deque, Optional, Sequence, TextIO, Tuple, TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from pytorch_pfn_extras.training.manager import _BaseExtensionsManager\n\n\nif os.name == 'nt':\n    import ctypes\n    from ctypes import windll  # type: ignore [attr-defined]\n\n    _STD_OUTPUT_HANDLE = -11\n\n    _COORD = ctypes.wintypes._COORD\n\n    class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):\n        _fields_ = [('dwSize', _COORD), ('dwCursorPosition', _COORD),\n                    ('wAttributes', ctypes.c_ushort),\n                    ('srWindow', ctypes.wintypes.SMALL_RECT),\n                    ('dwMaximumWindowSize', _COORD)]\n\n    def set_console_cursor_position(x: int, y: int) -> None:\n        \"\"\"Set relative cursor position from current position to (x,y)\"\"\"\n\n        whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)\n        csbi = _CONSOLE_SCREEN_BUFFER_INFO()\n        windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))\n        cur_pos = csbi.dwCursorPosition\n        pos = _COORD(cur_pos.X + x, cur_pos.Y + y)\n\n        # Workaround the issue that pyreadline overwrites the argtype\n        setpos = windll.kernel32.SetConsoleCursorPosition\n        argtypes = setpos.argtypes\n        setpos.argtypes = None\n        setpos(whnd, pos)\n        setpos.argtypes = argtypes\n\n    def erase_console(x: int, y: int, mode: int = 0) -> None:\n        \"\"\"Erase screen.\n\n        Mode=0: From (x,y) position down to the bottom of the screen.\n        Mode=1: From (x,y) position down to the beginning of line.\n        Mode=2: Hole screen\n        \"\"\"\n\n        whnd = windll.kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)\n        csbi = _CONSOLE_SCREEN_BUFFER_INFO()\n        windll.kernel32.GetConsoleScreenBufferInfo(whnd, ctypes.byref(csbi))\n        cur_pos = csbi.dwCursorPosition\n        wr = ctypes.c_ulong()\n        if mode == 0:\n            num = csbi.srWindow.Right * (\n                csbi.srWindow.Bottom - cur_pos.Y) - cur_pos.X\n            windll.kernel32.FillConsoleOutputCharacterA(\n                whnd, ord(' '), num, cur_pos, ctypes.byref(wr))\n        elif mode == 1:\n            num = cur_pos.X\n            windll.kernel32.FillConsoleOutputCharacterA(\n                whnd, ord(' '), num, _COORD(0, cur_pos.Y), ctypes.byref(wr))\n        elif mode == 2:\n            os.system('cls')\n\n\nclass ProgressBar:\n\n    def __init__(self, out: Optional[TextIO] = None) -> None:\n        self._out = sys.stdout if out is None else out\n        self._recent_timing: Deque[Tuple[int, float, float]] = collections.deque(\n            [], maxlen=100)\n\n    def update_speed(\n            self,\n            iteration: int,\n            epoch_detail: float\n    ) -> Tuple[float, float]:\n        now = time.time()\n        self._recent_timing.append((iteration, epoch_detail, now))\n        old_t, old_e, old_sec = self._recent_timing[0]\n        span = now - old_sec\n        if span != 0:\n            speed_t = (iteration - old_t) / span\n            speed_e = (epoch_detail - old_e) / span\n        else:\n            speed_t = float('inf')\n            speed_e = float('inf')\n        return speed_t, speed_e\n\n    def get_lines(self) -> Sequence[str]:\n        raise NotImplementedError\n\n    def update(\n            self,\n            manager: Optional['_BaseExtensionsManager'] = None\n    ) -> None:\n        self.erase_console()\n\n        lines = self.get_lines()\n        for line in lines:\n            self._out.write(line)\n\n        self.move_cursor_up(len(lines))\n        self.flush()\n\n    def close(self) -> None:\n        self.erase_console()\n        self.flush()\n\n    def erase_console(self) -> None:\n        if os.name == 'nt':\n            erase_console(0, 0)\n        else:\n            self._out.write('\\033[J')\n\n    def move_cursor_up(self, n: int) -> None:\n        # move the cursor to the head of the progress bar\n        if os.name == 'nt':\n            set_console_cursor_position(0, - n)\n        else:\n            self._out.write('\\033[{:d}A'.format(n))\n\n    def flush(self) -> None:\n        if hasattr(self._out, 'flush'):\n            self._out.flush()\n", "path": "pytorch_pfn_extras/training/extensions/util.py"}]}