473,799 Members | 2,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Namespaces and the timeit module

I'm playing with the timeit module, and can't figure out how to time a
function call. I tried:

def foo ():
x = 4
return x

t = timeit.Timer ("foo()")
print t.timeit()

and quickly figured out that the environment the timed code runs under
is not what I expected:

Traceback (most recent call last):
File "./d.py", line 10, in ?
print t.timeit()
File "/usr/local/lib/python2.3/timeit.py", line 158, in timeit
return self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
NameError: global name 'foo' is not defined

In fact, trying to time "print dir()" gets you:

['_i', '_it', '_t0', '_timer']

It seems kind of surprising that I can't time functions. Am I just not
seeing something obvious?
Jul 18 '05 #1
2 2469
Roy Smith <ro*@panix.co m> writes:
I'm playing with the timeit module, and can't figure out how to time a
function call. I tried:

def foo ():
x = 4
return x

t = timeit.Timer ("foo()")
print t.timeit()

and quickly figured out that the environment the timed code runs under
is not what I expected:

Traceback (most recent call last):
File "./d.py", line 10, in ?
print t.timeit()
File "/usr/local/lib/python2.3/timeit.py", line 158, in timeit
return self.inner(it, self.timer)
File "<timeit-src>", line 6, in inner
NameError: global name 'foo' is not defined

In fact, trying to time "print dir()" gets you:

['_i', '_it', '_t0', '_timer']

It seems kind of surprising that I can't time functions. Am I just not
seeing something obvious?


Like the documentation for Timer? :-)

class Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])

You can't use statements defined elsewhere, you have to define them in
the setup arguments (as a string). Like this:
define_foo = '''
def foo():
x = 4
return x
'''

t = timeit.Timer("f oo()" setup=define_fo o)
print t.timeit()
One common idiom I've seen is to put your definition of foo() in a
module (say x.py), then, from the command line:

$ python -m timeit -s 'from x import foo' 'foo()'

(the -m is for python 2.4 to run the timeit module; use the full path
to timeit.py instead for earlier pythons)

Alternatively, the examples for the timeit module has another way to
time functions defined in a module.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)phy sics(dot)mcmast er(dot)ca
Jul 18 '05 #2
co**********@ph ysics.mcmaster. ca (David M. Cooke) wrote:
It seems kind of surprising that I can't time functions. Am I just not
seeing something obvious?


Like the documentation for Timer? :-)

class Timer([stmt='pass' [, setup='pass' [, timer=<timer function>]]])

You can't use statements defined elsewhere, you have to define them in
the setup arguments (as a string).


Doh! Of course. Now that you point it out, it makes perfect sense, but
I didn't get that from reading the description. Thanks.
Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
423
by: Michele Simionato | last post by:
I use a little wrapper to timeit: $ cat timeit_.py import timeit, __main__, warnings warnings.filterwarnings('ignore', 'import \* only allowed at module level',SyntaxWarning) def timeit(stmt, setup='from __main__ import *', n=1000): t = timeit.Timer(stmt,setup)
5
1956
by: ChaosKCW | last post by:
Hi I was wondering if someone could help with the import statements needed to use the timeit module in the following code. I need to access the "cur" object. Thanks, import cx_Oracle import timeit
2
2703
by: Steven D'Aprano | last post by:
When using the timeit module, you pass the code you want to time as strings: import timeit t = timeit.Timer("foo(x, y)", \ """from module import foo x = 27 y = 45 """) elapsed_time = t.timeit()
2
3309
by: Steven D'Aprano | last post by:
The timeit module is ideal for measuring small code snippets; I want to measure large function objects. Because the timeit module takes the code snippet argument as a string, it is quite handy to use from the command line, but it is less convenient for timing large pieces of code or when working in the interactive interpreter. E.g. variations on this *don't* work: $ python Python 2.4.3 (#1, Jun 13 2006, 11:46:08)
0
10482
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10251
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10225
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.