Skip to content

Commit

Permalink
Added timing utilities timedcall, timedcalls
Browse files Browse the repository at this point in the history
  • Loading branch information
dheerosaur committed May 12, 2012
1 parent 13487cc commit 463f2bc
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions cs212/zebra.py
Expand Up @@ -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
Expand Down Expand Up @@ -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.