用Python测量脚本运行时间

RGS*_*RGS 5 python runtime python-3.x

我已经有这个问题很长一段时间了,我在几个地方寻找答案,没有成功......

我的问题:如何衡量给定脚本完全完成所需的时间?

想象一下,我有这个愚蠢的脚本来计算从0到10 ^ 12的所有数字的总和:

x = 0
for i in range(pow(10,12)):
    x += i
print(x)
Run Code Online (Sandbox Code Playgroud)

我怎么知道我的电脑完成了多长时间?

在此先感谢RSerrao

jac*_*wah 11

您可以使用python profiler cProfile来测量CPU时间,以及每个函数内部花费的时间以及每个函数调用的次数.如果要在不知道瓶颈位置的情况下提高脚本性能,这非常有用.对另一个SO问题的答案非常好.在文档中查看也总是好的.

以下是如何使用命令行中的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}
Run Code Online (Sandbox Code Playgroud)


RGS*_*RGS 3

我已经知道你可以做一件聪明的事情:

import time
# at the beginning:
start_time = time.time()

# at the end of the program:
print("%f seconds" % (time.time() - start_time))
Run Code Online (Sandbox Code Playgroud)

它不是 100% 准确,但对我的目的来说相当好