<分区>
这个问题我想了很久,找了好几个地方都没有成功...
我的问题:如何衡量给定脚本完全完成所需的时间?
想象一下,我有这个愚蠢的脚本来计算从 0 到 10^12 的所有数字的总和:
x = 0
for i in range(pow(10,12)):
x += i
print(x)
我怎么知道我的 PC 花了多少时间来完成它?
提前致谢, RSerrao
<分区>
这个问题我想了很久,找了好几个地方都没有成功...
我的问题:如何衡量给定脚本完全完成所需的时间?
想象一下,我有这个愚蠢的脚本来计算从 0 到 10^12 的所有数字的总和:
x = 0
for i in range(pow(10,12)):
x += i
print(x)
我怎么知道我的 PC 花了多少时间来完成它?
提前致谢, RSerrao
最佳答案
您可以使用 python 分析器 cProfile 来测量 CPU time以及每个函数内部花费了多少时间以及每个函数被调用了多少次。如果您想在不知道瓶颈在哪里的情况下提高脚本的性能,这将非常有用。 This answer另一个SO问题很好。看看the docs总是好的也是。
这是一个如何从命令行使用 cProfile 分析脚本的示例:
$ python -m cProfile euler048.py
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
关于python - 在 Python 中测量脚本运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20874387/