Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python profiling

I wrote a couple of modules in Python for generating factorials and I want to test the running time. I found an example of profiling here and I used that template to profile my modules:

import profile #fact

def main():
    x = raw_input("Enter number: ")
    profile.run('fact(int(x)); print')
    profile.run('factMemoized(int(x)); print')

def fact(x):
    if x == 0: return 1
    elif x < 2: return x
    else:
        return x * fact(x-1)

def factMemoized(x):
    if x == 0: return 1
    elif x < 2: return x
    dict1 = dict()
    dict1[0] = 1
    dict1[1] = 1
    for i in range (0, x+1):
        if dict1.has_key(i): pass
        else: dict1[i] = i * dict1[i-1]
    return dict1[x]

if __name__ == "__main__":
    main()

However, I get the following error:

Enter number: 10
Traceback (most recent call last):
  File "fact.py", line 32, in <module>
    main()
  File "fact.py", line 7, in main
    profile.run('fact(int(x)); x')
  File "C:\Python27\lib\profile.py", line 70, in run
    prof = prof.run(statement)
  File "C:\Python27\lib\profile.py", line 447, in run
    return self.runctx(cmd, dict, dict)
  File "C:\Python27\lib\profile.py", line 453, in runctx
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined

Any idea what I'm doing wrong here? TIA! ~craig

like image 513
Craig Avatar asked Dec 04 '22 20:12

Craig


1 Answers

As John Gaines Jr. said, profile.run() has some scoping problems. However, you can just use runctx with globals() and locals() and provide the context explicitly:

profile.runctx('fact(int(x)); print', globals(), locals())

Explicit is better than implicit :)

like image 69
Petr Viktorin Avatar answered Dec 27 '22 10:12

Petr Viktorin