Difference between revisions of "Python - timers"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) (Created page with '=Timers= <pre> #----------------------------- # High Resolution Timers t1 = time.clock() # Do Stuff Here t2 = time.clock() print t2 - t1 # 2.27236813618 # Accuracy will depen...') |
PeterHarding (talk | contribs) |
||
Line 1: | Line 1: | ||
=Timers= | =Timers= | ||
Also see: http://pleac.sourceforge.net/pleac_python/datesandtimes.html | |||
<pre> | <pre> |
Latest revision as of 21:54, 18 October 2010
Timers
Also see: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
#----------------------------- # High Resolution Timers t1 = time.clock() # Do Stuff Here t2 = time.clock() print t2 - t1 # 2.27236813618 # Accuracy will depend on platform and OS, # but time.clock() uses the most accurate timer it can time.clock(); time.clock() # 174485.51365466841 # 174485.55702610247 #----------------------------- # Also useful; import timeit code = '[x for x in range(10) if x % 2 == 0]' eval(code) # [0, 2, 4, 6, 8] t = timeit.Timer(code) print "10,000 repeats of that code takes:", t.timeit(10000), "seconds" print "1,000,000 repeats of that code takes:", t.timeit(), "seconds" # 10,000 repeats of that code takes: 0.128238644856 seconds # 1,000,000 repeats of that code takes: 12.5396490336 seconds #----------------------------- import timeit code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()' t = timeit.Timer(code) print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times." print "Average Time:", t.timeit(1000) / 1000 # Time taken: 5.24391507859 Short Sleeps #----------------------------- # Short Sleeps seconds = 3.1 time.sleep(seconds) print "boo"