Python 定时器是否能够在同一个定时器对象中测量多个间隔?我有一个程序可以循环数千个对象并执行多个操作,例如:下载、处理、存储、分析。我希望能够测量多次执行时每个单独步骤的累积时间,但在执行其他操作的较大代码块中。
有什么方法可以启动然后停止(暂停)计时器,然后重新启动它们以测量更多时间?类似于下面的伪代码?
import timeit
download_timer = <create a timer>
processing_timer = <create a timer>
for item_id in big_list_of_items:
download_timer.start()
slow_response = download_data(item_id)
download_timer.pause()
processing_timer.start()
munge_data(slow_response)
processing_timer.pause()
log.debug('Cumulative download time: {} sec'.format(download_timer.elapsed))
log.debug('Cumulative data processing time: {} sec'.format(processing_timer.elapsed))
我目前正在每个循环上创建一个新计时器,然后我必须跟踪添加每个增量的多个变量中的时间。仔细阅读文档,这看起来是最好的选择,不需要创建我自己的类来执行此操作,但我希望有人知道一种更简单的方法。
我会做一些这样的事情:
import time
from time import perf_counter_ns
def download_data(item_id):
time.sleep(.5)
def munge_data(response):
time.sleep(0.1)
big_list_of_items = [1, 2, 3, 4, 5]
download_time = 0
processing_time = 0
for item_id in big_list_of_items:
download_timer_start = perf_counter_ns()
slow_response = download_data(item_id)
download_timer_stop = perf_counter_ns()
download_time += download_timer_stop - download_timer_start
processing_timer_start = perf_counter_ns()
munge_data(slow_response)
processing_timer_stop = perf_counter_ns()
processing_time += processing_timer_stop - processing_timer_start
print(f"Cumulative download time: {download_time / 1_000_000_000} seconds")
print(f"Cumulative data processing time: {processing_time / 1_000_000_000} seconds")
终端有点像这样:
Cumulative download time: 2.52 seconds
Cumulative data processing time: 0.52 seconds