首先导入time模块,在程序执行开始start=time.time(),在程序执行结束后加入end=time.time(),则end-start就是这段程序运行的时间
import time def sum(n): start=time.time() theSum=0 for i in range(1,n+1): theSum=theSum+i end=time.time() return theSum,end-start
for j in range(5): print("sum id %d ,time is %10.7f"% sum(100000))
运行结果:sum id 5000050000 ,time is 0.0090039 sum id 5000050000 ,time is 0.0120089 sum id 5000050000 ,time is 0.0120089 sum id 5000050000 ,time is 0.0090044 sum id 5000050000 ,time is 0.0110099