计数器:一个简单的进度计数器
一个简单的进度计,用于打印for循环执行中的迭代次数和经过的时间。
> 从 mlxtend.utils 导入 Counter
概述
Counter
类实现了一个用于显示for循环中迭代次数和经过时间的对象。请注意,Counter
的实现是为了效率;因此,Counter
仅提供非常基本的功能,以避免相对昂贵的评估(如if-else语句)。
参考文献
- -
示例 1 - 统计 for 循环中的迭代次数
from mlxtend.utils import Counter
import time
cnt = Counter()
for i in range(20):
# 进行一些计算
time.sleep(0.1)
cnt.update()
20 iter | 2 sec
请注意,第一个数字显示当前迭代,而第二个数字显示在初始化Counter
后经过的时间。
API
Counter(stderr=False, start_newline=True, precision=0, name=None)
Class to display the progress of for-loop iterators.
Parameters
-
stderr
: bool (default: True)Prints output to sys.stderr if True; uses sys.stdout otherwise.
-
start_newline
: bool (default: True)Prepends a new line to the counter, which prevents overwriting counters if multiple counters are printed in succession. precision: int (default: 0) Sets the number of decimal places when displaying the time elapsed in seconds.
-
name
: string (default: None)Prepends the specified name before the counter to allow distinguishing between multiple counters.
Attributes
-
curr_iter
: intThe current iteration.
-
start_time
: floatThe system's time in seconds when the Counter was initialized.
-
end_time
: floatThe system's time in seconds when the Counter was last updated.
Examples
>>> cnt = Counter()
>>> for i in range(20):
... # do some computation
... time.sleep(0.1)
... cnt.update()
20 iter | 2 sec
>>> print('The counter was initialized.'
' %d seconds ago.' % (time.time() - cnt.start_time))
The counter was initialized 2 seconds ago
>>> print('The counter was last updated'
' %d seconds ago.' % (time.time() - cnt.end_time))
The counter was last updated 0 seconds ago.
For more usage examples, please see https://rasbt.github.io/mlxtend/user_guide/utils/Counter/
Methods
update()
Print current iteration and time elapsed.