如何测量python中代码行之间的时间? [英] How to measure time taken between lines of code in python?
问题描述
因此,在Java中,我们可以如何测量函数执行所需的时间
So in Java, we can do How to measure time taken by a function to execute
但是如何在python中完成呢?要测量代码行之间的时间开始和结束时间? 这样做的事情:
But how is it done in python? To measure the time start and end time between lines of codes? Something that does this:
import some_time_library
starttime = some_time_library.some_module()
code_tobe_measured()
endtime = some_time_library.some_module()
time_taken = endtime - starttime
推荐答案
If you want to measure CPU time, can use time.process_time()
for Python 3.3 and above:
import time
start = time.process_time()
# your code here
print(time.process_time() - start)
第一个电话打开计时器,第二个电话告诉您已经过去了几秒钟.
First call turns the timer on, and second call tells you how many seconds have elapsed.
还有一个功能time.clock()
,但自弃用了,因为Python 3.3 ,并将在Python 3.8中删除.
There is also a function time.clock()
, but it is deprecated since Python 3.3 and will be removed in Python 3.8.
有更好的性能分析工具,例如timeit
和profile
,但是time.process_time()可以测量CPU时间,这就是您要问的问题.
There are better profiling tools like timeit
and profile
, however time.process_time() will measure the CPU time and this is what you're are asking about.
如果要测量挂钟时间,请使用time.time()
.
If you want to measure wall clock time instead, use time.time()
.
这篇关于如何测量python中代码行之间的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!