%time,%timeit和%% time
你想知道你的代码需要运行多长时间吗?不出所料,你需要使用的魔术命令是时间及其变体。这是对代码进行基准测试的快速方法,并向其他人表明他们需要多长时间来重新运行结果。
import numpy as np
from numpy.random import randint
# A function to simulate one million dice throws.
def one_million_dice():
return randint(low=1, high=7, size=1000000)
# Let's try %time first
%time throws = one_million_dice()
%time mean = np.mean(throws)
# Outputs:
# Wall time: 20.6 ms
# Wall time: 3.01 ms
# Let's do the same with %timeit
%timeit throws = one_million_dice()
%timeit mean = np.mean(throws)
# Outputs:
# 10 loops, best of 3: 22.2 ms per loop
# 100 loops, best of 3: 2.86 ms per loop
# And finally %%time
%%time
throws = one_million_dice()
mean = np.mean(throws)
# Outputs:
# Wall time: 36.6 ms
或者用python自己的库方法
方法1
import datetime
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now()
print (endtime - starttime).seconds
方法 2start = time.time()
run_fun()
end = time.time()
print end-start
方法3start = time.clock()
run_fun()
end = time.clock()
print end-start
方法1和方法2都包含了其他程序使用CPU的时间,是程序开始到程序结束的运行时间。 方法3算只计算了程序运行的CPU时间