python - 在 Python 中测量脚本运行时间

标签 python python-3.x runtime

<分区>

这个问题我想了很久,找了好几个地方都没有成功...

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

想象一下,我有这个愚蠢的脚本来计算从 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/

相关文章:

Python:更改来自函数参数的全局变量

java - 对进程执行命令

python - 在 python odoo 中格式化字符串

python - 如何使用用户输入创建类实例?

python - def 在odoo 10、python 中创建带有many2one 字段的函数

python - self 指的是新创建的对象;在其他类方法中,它指的是调用其方法的实例。

python - _tkinter.Tcl错误: unknown option "-image"

python - 根据初始参数的值向 argparse 添加参数

unity-game-engine - 如何在运行时操纵地形的形状区域 - Unity 3D

c++ - 用 C 或汇编制作一个简单的 CRT0