我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
当前回答
给定要计时的函数,
测试.py:
def foo():
# print "hello"
return "hello"
使用timeit的最简单方法是从命令行调用它:
% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
不要尝试使用time.time或time.clock(天真地)来比较函数的速度。他们会给出误导性的结果。
PS.不要将打印语句放在您希望计时的函数中;否则测量的时间将取决于终端的速度。
其他回答
import time
def getElapsedTime(startTime, units):
elapsedInSeconds = time.time() - startTime
if units == 'sec':
return elapsedInSeconds
if units == 'min':
return elapsedInSeconds/60
if units == 'hour':
return elapsedInSeconds/(60*60)
使用探查器模块。它提供了非常详细的概况。
import profile
profile.run('main()')
它输出类似于:
5 function calls in 0.047 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 :0(exec)
1 0.047 0.047 0.047 0.047 :0(setprofile)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 0.047 0.047 profile:0(main())
1 0.000 0.000 0.000 0.000 two_sum.py:2(twoSum)
我发现它很有启发性。
这是一种很晚的反应,但也许对某人来说是有目的的。这是一种我认为非常干净的方法。
import time
def timed(fun, *args):
s = time.time()
r = fun(*args)
print('{} execution took {} seconds.'.format(fun.__name__, time.time()-s))
return(r)
timed(print, "Hello")
请记住,“print”是Python 3中的函数,而不是Python 2.7中的函数。但是,它可以与任何其他功能一起使用。干杯
我为此做了一个库,如果你想测量一个函数,你可以这样做
from pythonbenchmark import compare, measure
import time
a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]
@measure
def myFunction(something):
time.sleep(0.4)
@measure
def myOptimizedFunction(something):
time.sleep(0.2)
myFunction(input)
myOptimizedFunction(input)
https://github.com/Karlheinzniebuhr/pythonbenchmark
在python3上:
from time import sleep, perf_counter as pc
t0 = pc()
sleep(1)
print(pc()-t0)
优雅而短小。