Python代码的定时执行速度

时间:2012-02-23 23:30:23

标签: python performance

  

可能重复:
  Python: Time a code segment for testing performance (with timeit)

在C ++中,您可以非常轻松地计算代码块,请参阅下面的代码。有没有办法做这个python? (轻松)谢谢!

time_t startTime = clock();

// Do stuff

time_t endTime = clock();

cout << "Difference in time(milliseconds) : " << endTime - startTime << endl;

4 个答案:

答案 0 :(得分:10)

尝试使用标准库中提供的profilers

以下是如何使用命令行中的cProfile来分析脚本的示例。 cProfile是所有Python发行版中可用的分析器之一。

$ 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}

答案 1 :(得分:7)

代码的逐字翻译

import datetime
start = datetime.datetime.now()
// do stuff
finish = datetime.datetime.now()
print finish-start

答案 2 :(得分:4)

您可能希望查看timeit module,这对于计算小代码片段非常方便。

典型示例:

from timeit import Timer

def foo():
    # some code here

t1 = Timer("""foo()""", """from __main__ import foo""")
print t1.timeit(1000)  # runs foo() 1000 times and returns the time taken

答案 3 :(得分:1)

我打破了你想要进入一个函数的部分,并在它周围加上一个定时装饰器来代码。

这节省了代码重复,并增加了你可以存储/记录函数名称和args以及时间统计数据的好处。

相关问题