首页 > 代码库 > 计算程序运行时间

计算程序运行时间

 

摘自Cookbook:

 1 #!/usr/bin/env python 2 import time 3 def timeo(fun, n=1000): 4     def void(  ): pass 5     start = time.clock(  ) 6     for i in range(n): void(  ) 7     stend = time.clock(  ) 8     overhead = stend - start 9     start = time.clock(  )10     for i in range(n): fun(  )11     stend = time.clock(  )12     thetime = stend-start13     return fun._ _name_ _, thetime-overhead14 to500 = {}15 for i in range(500): to500[i] = 116 evens = {}17 for i in range(0, 1000, 2): evens[i] = 118 def simpleway(  ):19     result = []20     for k in to500.keys(  ):21         if evens.has_key(k):22             result.append(k)23     return result24 def pyth22way(  ):25     return [k for k in to500 if k in evens]26 def filterway(  ):27     return filter(evens.has_key, to500.keys(  ))28 def badsloway(  ):29     result = []30     for k in to500.keys(  ):31         if k in evens.keys(  ):32             result.append(k)33     return result34 for f in simpleway, pyth22way, filterway, badsloway:35     print "%s: %.2f"%timeo(f)

 

计算程序运行时间