我想测量执行一个函数所花费的时间。我没时间工作:

import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

当前回答

仅Python 3:

由于从Python 3.3开始,time.cclock()已被弃用,因此您将希望使用time.perf_counter()进行系统范围的计时,或使用time.process_time()进行进程范围的计时(就像您以前使用time.cclok()的方式一样):

import time

t = time.process_time()
#do some stuff
elapsed_time = time.process_time() - t

新函数process_time将不包括睡眠期间经过的时间。

其他回答

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)

我为此做了一个库,如果你想测量一个函数,你可以这样做


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

我们还可以将时间转换为人类可读的时间。

import time, datetime

start = time.clock()

def num_multi1(max):
    result = 0
    for num in range(0, 1000):
        if (num % 3 == 0 or num % 5 == 0):
            result += num

    print "Sum is %d " % result

num_multi1(1000)

end = time.clock()
value = end - start
timestamp = datetime.datetime.fromtimestamp(value)
print timestamp.strftime('%Y-%m-%d %H:%M:%S')

使用time.time()测量两点之间经过的墙上时钟时间:

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

这给出了以秒为单位的执行时间。


Python 3.3之后的另一个选项可能是使用perf_counter或process_time,具体取决于您的需求。在3.3之前,建议使用time.clock(感谢Amber)。但是,它目前已被弃用:

在Unix上,将当前处理器时间作为浮点数返回以秒表示。准确度,事实上就是定义“处理器时间”的含义取决于C函数的含义具有相同名称。在Windows上,此函数返回自该函数的第一次调用,作为浮点数,基于Win32函数QueryPerformanceCounter()。分辨率通常为优于一微秒。自3.3版起已弃用:此函数的行为取决于在平台上:改用perf_counter()或process_time(),根据您的要求,要有明确的行为。

测量时间(秒):

from timeit import default_timer as timer
from datetime import timedelta

start = timer()

# ....
# (your code runs here)
# ...

end = timer()
print(timedelta(seconds=end-start))

输出:

0:00:01.946339