前言
有时我们多次重复调用一个程序,每次调用因为输入不同,运行时间也不同,为了统计时间分布可用如下程序。
例子
假设有log文件内容如下:
Time of solve this question is : CPU : 13.4 : User : 13.1
Time of solve this question is : CPU : 12.1 : User : 12.3
Time of solve this question is : CPU : 15.3 : User : 13.4
…
我们想统计总时间,以及平均一个case运行的时间,则可以用如下的代码:
import re
def init():
f = open("log")
lines = f.readlines()
time = 0.0
cnt = 0
for line in lines:
t = re.findall(r'\d+\.?\d*', line)
time = time + float(t[0])
cnt = cnt + 1
print("Total time is : ", time)
print("The number of case : ", cnt)
print("Average time of one case is : ", time/cnt)
if __name__ == "__main__":
init()
程序运行结果为:
Total time is : 40.8
The number of case : 3
Average time of one case is : 13.6