Skip to content
Browse files

Added timing utilities timedcall, timedcalls

  • Loading branch information...
1 parent 13487cc commit 463f2bcd9f651707c6bbfea561fdf33b0f3fb8f3 @dheerosaur committed May 12, 2012
Showing with 25 additions and 0 deletions.
  1. +25 −0 cs212/zebra.py
View
25 cs212/zebra.py
@@ -23,8 +23,10 @@
# Each house is painted a different color, and their inhabitants are of different nationalities,
# own different pets, drink different beverages and smoke different brands of American cigarettes.
+import time
import itertools
+
def imright(h1, h2):
"House h1 is immediately right of h2 if h1-h2 == 1."
return h1-h2 == 1
@@ -59,5 +61,28 @@ def zebra_puzzle():
if nextto(Kools, horse)
)
+
+def timedcall(fn, *args):
+ "Call function with args; return the time in seconds and result."
+ t0 = time.clock()
+ result = fn(*args)
+ t1 = time.clock()
+ return t1-t0, result
+
+def average(numbers):
+ "Return the average (arithmetic mean) of a sequence of numbers."
+ return sum(numbers) / float(len(numbers))
+
+def timedcalls(n, fn, *args):
+ """If n is an int, call fn(*args) n times. If it is a float,
+ call it till n seconds are over. Return min, avg, max of times"""
+ if isinstance(n, int):
+ times = [timedcall(fn, *args)[0] for i in range(n)]
+ else:
+ times = []
+ while sum(times) < n:
+ times.append(timedcall(fn, *args)[0])
+ return min(times), average(times), max(times)
+
if __name__ == '__main__':
print "%s drinks water and %s owns the zebra" % zebra_puzzle()

0 comments on commit 463f2bc

Please sign in to comment.
Something went wrong with that request. Please try again.