BOMBOLOM.COM

(python) Checking a function execution time

Posted by José Lopes

You may need to know the for a certain function the time it takes to be executed.
The reasons for this can be, for instance, to optimize the function or check the fastest solution to a problem among severel.

This post provides a generic solution to check a function execution time.

The solution is very simple and can be used anywhere.

(1)import time
(2)def timer (f, *args):
(3)  begin = time.time()
(4)  f(*args)
(5)  end = time.time()
(6)  total = end - begin
(7)  print total

Explaining the code:

(1) Imports the time module.
(2) Declaring the function to calculate the time, taking another function f that will be evaluate and any number of arguments (*args).
(3) and (5) Record the time before and after executing the fuction f.
(4) Runs the given f function.
(6) Calculates the execution time.
(7) Prints to screen the execution time in seconds.

Here's an example how to use this function, with the goal to show how to declare the f function arguments to those who are not familiarize.
If you have a test function:

def test(x, y):
  value = x + y
  return value

Just do:

timer(test, 4, 6)

Has you can see, declaring on the time function all the test function arguments you have a real generic solution.

2007.09.10 | There's more... | Comments 0 | Tags ,

Deixe a sua mensagem:

Nome:


E-mail:


URL:


Comment:

Secret number

To send you comment you must insert the "secret number" on the box


Made with PyBlosxom | Add to Google