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

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

当前回答

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

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')

其他回答

还有一种使用timeit的方法:

from timeit import timeit

def func():
    return 1 + 1

time = timeit(func, number=1)
print(time)

对于Python 3

如果使用时间模块,则可以获取当前时间戳,然后执行代码,然后再次获取时间戳。现在,所用时间将是第一个时间戳减去第二个时间戳:

import time

first_stamp = int(round(time.time() * 1000))

# YOUR CODE GOES HERE
time.sleep(5)

second_stamp = int(round(time.time() * 1000))

# Calculate the time taken in milliseconds
time_taken = second_stamp - first_stamp

# To get time in seconds:
time_taken_seconds = round(time_taken / 1000)
print(f'{time_taken_seconds} seconds or {time_taken} milliseconds')

(仅使用Ipython)您可以使用%timeit来测量平均处理时间:

def foo():
    print "hello"

然后:

%timeit foo()

结果如下:

10000 loops, best of 3: 27 µs per loop

我喜欢简单(python 3):

from timeit import timeit

timeit(lambda: print("hello"))

单个执行的输出为微秒:

2.430883963010274

说明:timeit默认执行匿名函数100万次,结果以秒为单位。因此,1次执行的结果相同,但平均以微秒为单位。


对于速度较慢的操作,添加较少的迭代次数,否则您可能会一直等待:

import time

timeit(lambda: time.sleep(1.5), number=1)

总迭代次数的输出始终以秒为单位:

1.5015795179999714

使用探查器模块。它提供了非常详细的概况。

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)

我发现它很有启发性。