473,809 Members | 2,757 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 2473
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
3310
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
10635
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
10376
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
10378
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
9198
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7653
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
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
5550
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...
1
4332
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
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.