【问题标题】:How to check the number of executed operations in the past x minutes in Python?如何在 Python 中检查过去 x 分钟内执行的操作数?
【发布时间】:2018-04-18 12:46:57
【问题描述】:
例如:
for i range(1,9999):
#foo() is an operation that has varying execution time.
foo(i);
check_number_of_foo_executed_last_60_sec();
在for循环的中间,如何检查有多少foo()在过去60秒内被执行了?
除了将每个foo()的执行时间存储在一个列表中,还有其他方法吗?
【问题讨论】:
标签:
python
performance
time
【解决方案1】:
import threading
count = 0
timer = None
try:
def print_count():
global timer
timer = threading.Timer(5.0, print_count)
timer.start()
print count
print_count()
for i in range(1,9999):
foo(i)
count += 1
finally:
if timer is not None:
timer.cancel()
【解决方案2】:
Python 可以重用的一种聪明方法是signal.SIGALRM:
最棒的是,它
- 需要对源代码进行零更改
和
- 即使在“阻塞”计算期间也可以工作:
我甚至将它用于进程级别的上下文切换(以及某些平台偷偷降低 CPU 时间)的监控,通过套接字与外部进程监控平台进行通信,即使 GIL 不允许这种“交错”操作(在繁重的 numpy 处理期间,不喜欢在高强度数字运算中环顾四周)
########################################################################
### SIGALRM_handler_
###
def SIGALRM_handler_ConstTIME( aSigNUM, aFRAME ):
try:
global i
print( "INF:: {0: >6d}x".format( i ) )
except:
pass
##########
# FINALLY:
#
signal.signal( signal.SIGALRM, SIGALRM_handler_ConstTIME ) # .ASSOC { SIGALRM: thisHandler }
signal.setitimer( signal.ITIMER_REAL, 60, 60 ) # .SET @60 [sec] interval, after first run, starting after 60[sec] initial-delay
...
INF:: 28x
INF:: 62x
INF:: 97x
...
signal.setitimer( signal.ITIMER_REAL, 0, 5 ) # .UNSET
#############################################################################