计算程序运行时间

 

摘自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-start
13     return fun._ _name_ _, thetime-overhead
14 to500 = {}
15 for i in range(500): to500[i] = 1
16 evens = {}
17 for i in range(0, 1000, 2): evens[i] = 1
18 def simpleway(  ):
19     result = []
20     for k in to500.keys(  ):
21         if evens.has_key(k):
22             result.append(k)
23     return result
24 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 result
34 for f in simpleway, pyth22way, filterway, badsloway:
35     print "%s: %.2f"%timeo(f)

 

posted @ 2014-12-09 20:46  MDGSF  阅读(133)  评论(0编辑  收藏  举报