On Sunday 7 Jun 2015 08:39 CEST, Cecil Westerhof wrote: > Sometimes I just want to know how much time a function takes, but at > the same time I also want the result of the function. For this I > wrote the following function: def time_test(function, *args): > startTime = time.time() results = function(*args) endTime = > time.time() print('It took {0} seconds'.format(endTime - startTime)) > return results > > I can do: > time_test(test_random, 100, 10 ** 5) > This outputs: > It took 17.01685857772827 seconds > and returns: > (98592, 100833, 0.977775133140936) > > When executing: > time_test(test_random, 100, 10 ** 6) > it outputs: > It took 165.26371836662292 seconds > and returns: > (997103, 1002009, 0.9951038363926871)
I improved a little on the function: def time_test(function, arguments, print_time = True): start_time = time.time() results = function(*arguments) end_time = time.time() used_time = end_time - start_time if print_time: print('It took {0} seconds'.format(used_time)) else: results = (used_time, results) return results Default the function still prints the time, but it also possible to return the time with the results. Also the arguments are given as a tuple now. With the following function: def test_random(length, multiplier = 10000): number_list = length * [0] for i in range(length * multiplier): number_list[random.randint(0, length - 1)] += 1 minimum = min(number_list) maximum = max(number_list) return (minimum, maximum, minimum / maximum) The call: time_test(test_random, (100, 10 ** 5)) outputs: It took 15.95521855354309 seconds and gives: (98870, 100810, 0.9807558773931158) And the call: time_test(test_random, (100, 10 ** 5), False) does not output anything and gives (15.926506280899048, (99146, 100779, 0.9837962273886425)) Of-course a new run will give a different result. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list