计时Python代码执行时间

8 投票
6 回答
20225 浏览
提问于 2025-04-18 02:01

我怎么才能知道Python代码的执行时间,单位是微秒呢?我试过用time.time和timeit.timeit,但结果总是不太理想。

6 个回答

0
from time import time
chrono = []
chrono.append(time())
# your code 1 here
chrono.append(time())
print "duration 1 is : ", str((chrono[1] - chrono.pop(0))*1e6), " µs"
# your code 2 here
chrono.append(time())
print "duration 2 is : ", str((chrono[1] - chrono.pop(0))*1e6), " µs"

编辑: 其实我是在一个函数里使用这个:我声明了一个变量 chronochrono = []),并在我想测量的第一段代码之前初始化它(chrono.append(time()))。然后我调用 print_time("一个有用的信息"),这个函数是这样定义的:

def print_time(message):
    chrono.append(time())
    timestamp = chrono[1] - chrono.pop(0)
    print message + ":\n {0}s".format(timestamp)

输出是:

a useful message:
0.123456789s

使用 chrono.pop(0) 时,最后插入的值会变成列表中的第一个,下一次调用 print_time 时就不需要管理列表里的项目了:它的长度始终是2,并且顺序是正确的。

1

一个很好的性能分析方法是使用 cProfile 库:

python -m cProfile [your_script].py

它会输出你代码中每个程序的执行时间、循环次数等等信息。

2

更新
我强烈推荐使用这个库 cProfile,然后用 snakeviz 来可视化结果。

这样你就能得到一个互动式的展示,能更清楚地了解你的代码在做什么。

你可以选择查看代码的特定部分,还有一个可以排序的表格,列出了所有函数及其运行时间。

忘掉我之前的回答和其他人的回答吧。直接使用snakeviz(我和snakeviz项目没有关系)。

snakevis时间展示

下面是原始回答

有一个非常好的库叫做 jackedCodeTimerPy

它能提供很好的报告,比如:

label            min          max         mean        total    run count
-------  -----------  -----------  -----------  -----------  -----------
imports  0.00283813   0.00283813   0.00283813   0.00283813             1
loop     5.96046e-06  1.50204e-05  6.71864e-06  0.000335932           50

我喜欢它能给你提供统计数据和计时器运行的次数。

使用起来很简单。如果我想测量一个for循环中代码的运行时间,我只需要这样做:

from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()

for i in range(50):
  JTimer.start('loop')  # 'loop' is the name of the timer
  doSomethingHere = 'This is really useful!'
  JTimer.stop('loop')
print(JTimer.report())  # prints the timing report

你还可以同时运行多个计时器。

JTimer.start('first timer')
JTimer.start('second timer')
do_something = 'amazing'
JTimer.stop('first timer')

do_something = 'else'
JTimer.stop('second timer')

print(JTimer.report())  # prints the timing report

在这个库的代码仓库里还有更多使用示例。希望这能帮到你。

https://github.com/BebeSparkelSparkel/jackedCodeTimerPY

6

最简单的方法大概是这样,不过这要求脚本至少运行十分之一秒:

import time
start_time = time.time()
# Your code here
print time.time() - start_time, "seconds"

还有一些性能分析工具可以帮助你。

假设我有一个这样的简单脚本:

print "Hello, World!"

我想要对它进行性能分析:

>python -m cProfile test.py
Hello, world!
         2 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 test.py:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}

这会显示运行花费了0.001秒,同时还提供了在执行代码时发生的其他调用信息。

8

试试这个,

import time
def main():
    print [i for i in range(0,100)]
    
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"

输出结果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0.00255163020819 seconds

更新

别忘了要 import time 这个库哦。

在你的代码之前加上这一行 start_time = time.clock(),然后在代码的最后加上

print time.clock() - start_time, "seconds" 来显示时间。

更新

# Top Of script file.
def main():
        print [i for i in range(0,100)]

start_time = time.clock()
#YOUR CODE HERE - 1

main()

#YOUR CODE HERE - N
print time.clock() - start_time, "seconds"

你还可以写一个装饰器来测量时间,

import time


def dec(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print(end - start)
    return wrapper


@dec
def test():
    for i in range(10):
        pass


test()
# output shows here 

撰写回答