How to measure time taken between lines of code in python?
所以在Java中,我们可以做如何测量函数执行所花费的时间
但它是如何在python中完成的? 要测量代码行之间的时间开始和结束时间?
这样做的东西:
1 2 3 4 5 6 7 | import some_time_library starttime = some_time_library.some_module() code_tobe_measured() endtime = some_time_library.some_module() time_taken = endtime - starttime |
如果要测量CPU时间,可以使用
1 2 3 4 | import time start = time.process_time() # your code here print(time.process_time() - start) |
第一个调用打开计时器,第二个调用告诉你已经过了多少秒。
还有一个函数
有更好的分析工具,如
如果您想要测量挂钟时间,请使用
您还可以使用
1 2 3 4 5 | start = time.time() #your code end = time.time() time_taken = end - start print('Time: ',time_taken) |
在小型便利类的帮助下,您可以测量缩进行所花费的时间,如下所示:
1 2 3 4 | with CodeTimer(): line_to_measure() another_line() # etc... |
在缩进行完成执行后将显示以下内容:
1 | Code block took: x.xxx ms |
更新:您现在可以使用
上述类的代码:
1 2 3 4 5 6 7 8 9 10 11 12 | import timeit class CodeTimer: def __init__(self, name=None): self.name =" '" + name +"'" if name else '' def __enter__(self): self.start = timeit.default_timer() def __exit__(self, exc_type, exc_value, traceback): self.took = (timeit.default_timer() - self.start) * 1000.0 print('Code block' + self.name + ' took: ' + str(self.took) + ' ms') |
然后,您可以命名要测量的代码块:
1 2 3 4 5 6 7 8 9 10 | with CodeTimer('loop 1'): for i in range(100000): pass with CodeTimer('loop 2'): for i in range(100000): pass Code block 'loop 1' took: 4.991 ms Code block 'loop 2' took: 3.666 ms |
并嵌套它们:
1 2 3 4 5 6 7 8 9 10 11 12 13 | with CodeTimer('Outer'): for i in range(100000): pass with CodeTimer('Inner'): for i in range(100000): pass for i in range(100000): pass Code block 'Inner' took: 2.382 ms Code block 'Outer' took: 10.466 ms |
关于
我总是喜欢以小时,分钟和秒(%H:%M:%S)格式检查时间:
1 2 3 4 5 6 | from datetime import datetime start = datetime.now() # your code end = datetime.now() time_taken = end - start print('Time: ',time_taken) |
输出:
1 | Time: 0:00:00.000019 |