This is the outline of a simple program
# some pre-defined constants
A = 1
B = 2
# function that does something critical
def foo(num1, num2):
# do something
# main program.... do something to A and B
for i in range(20):
# do something to A and B
# and update A and B during each iteration
import timeit
t = timeit.Timer(stmt="foo(num1,num2)")
print t.timeit(5)
I just keep getting "global name foo is not defined"..... Can anyone help me on this? Thanks!
I was playing around with timing in Python 3.7 today and trying to pass functions and variables into the timer. This is what I came up with.
This outputs:
Then all it takes to test a new version is adding in a new function. Something like:
Now it outputs:
The code snippets must be self-contained - they cannot make external references. You must define your values in the statement-string or setup-string:
Better yet, rewrite your code to not use global values.
Here is an example of how to compartmentalize the timing routine, without calling globals
You could even generalize this if you wanted to use the same
timeit
function to time other functions. Here is an example with your examplemain()
routine:There is a much simpler solution (at least for Python 3), you can cause the code to be executed within your current global namespace:
t = timeit.Timer(stmt="foo(num1,num2)", globals=globals())
https://docs.python.org/3/library/timeit.html#examples I know globals are not preferred, but if you are just making a quick script to check something I think this is the easiest implementation.
Your function needs to be define in the setup string. A good way to do this is by setting up your code in a module, so you simple have to do
Otherwise, you'll have to define all of the setup as a string inside the setup statement.
Something awesome I just found out about is a shortcut for iPython that uses cProfile.
This should work: