Timeit
This line will run this code a set number of times (1,000,000 by default!) and report the total time. The first parameter on this line is the code that you want to time. The second parameter is a special one-time setup. Since we are timing a user-defined function, we have to first import this function before timeit can call it. The last parameter is the number of times you want the statement to run.
模块的第一个参数为要执行计时的语句(statement)。按字符串的形式传入要执行的代码。第二个参数setup用于构建代码环境,可以用来导入需要的模块。最后的number指定了运行的次数。
import timeit
def read_to_list(user_input):
with open('4sbwinners.txt','r') as f:
winners = list(f)
return winners[user_input-1].strip()
def sequential_access(user_input):
with open('4sbwinners.txt','r') as f:
# Reads (and dumps) lines until we get to the user selection
for i in range(0,user_input-1):
f.readline()
winner = f.readline()
return winner.strip()
user_input = int(raw_input('Enter Super Bowl #: '))
while user_input < 1 or user_input > 4:
user_input = int(raw_input('Enter Super Bowl #: '))
seq_time = timeit.timeit('sequential_access({})'.format(user_input), \
'from __main__ import sequential_access',number=100000)
list_time = timeit.timeit('read_to_list({})'.format(user_input), \
'from __main__ import read_to_list',number=100000)
if seq_time < list_time:
pct = (list_time - seq_time) / seq_time
print 'Sequential access is {:.1f}% faster.'.format(pct * 100)
else:
pct = (seq_time - list_time) / list_time
print 'List access is {:.1f}% faster.'.format(pct * 100)
Notice the following two sample runs:
Enter Super Bowl #: 1
Sequential access is 7.1% faster.
Enter Super Bowl #: 4
Sequential access is 2.2% faster.