我想测量在Python程序中计算代码块所用的时间, 可能在用户cpu时间、系统cpu时间和运行时间之间分离。
我知道timeit
模块,但我有许多自己编写的函数,这并不容易
在安装过程中传递它们。
我宁愿要一些可以用的东西,比如:
#up to here I have done something....
start_counting() #or whatever command used to mark that I want to measure
#the time elapsed in the next rows
# code I want to evaluate
user,system,elapsed = stop_counting() #or whatever command says:
#stop the timer and return the times
用户和系统CPU时间不是必需的(尽管我想测量它们), 但在过去的一段时间里,我希望能够做这样的事情, 而不是使用复杂的命令或模块。
要以秒为单位获取经过的时间,可以使用^{} :
使用
timeit.default_timer()
而不是time.time()
或time.clock()
,因为它将为任何平台选择具有更高分辨率的计时函数。我发现自己一次又一次地解决这个问题,所以我最终为它创建了一个library。用
pip install timer_cm
安装。然后:输出:
我总是使用decorator为现有函数做一些额外的工作,包括获取执行时间。这是Python和简单。
相关问题 更多 >
编程相关推荐