473,395 Members | 1,497 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

timeit module for comparing the performance of two scripts

Hi,
Following are my files.
In the format:

Filename
----
content
----

config1.txt
----
#DataBase Repository file
dbRepository = omsa_disney.xml
----

config2.txt
----
# Configfile for sendmail

[Sendmail]
userprefix = testuser
----

pyConfig.py
----
import re

def pyConfig():
fhandle = open( 'config1.txt', 'r' )
arr = fhandle.readlines()
fhandle.close()

hash = {}

for item in arr:
txt = item.strip()
if re.search( '^\s*$', txt ):
continue
if re.search( '^#.*$', txt ):
continue
if not re.search( '^\s*(\w|\W)+\s*=\s*(\w|\W)+\s*$', txt ):
continue
hash[txt.split( '=' )[0].strip().lower()] = txt.split( '='
)[1].strip()

print hash['dbrepository']
----

pyConparse.py
----
from ConfigParser import ConfigParser

def pyConParse():
configparser = ConfigParser()
configparser.read('config2.txt')
print configparser.get('Sendmail','userprefix')

----

Question is:
How do I compare the performance of pyConfig.py vs pyConparse.py using
timeit module?
I tried it as the way it is mentioned in the example, but when I do
Timer("pyConfig()","from __main__ import pyConfig"), it imports
pyConfig in infinite loop. ( How does the python doc example on timeit
work? Anyone tried it?)

I just need to compare pyConfig.py and pyParse.py. ( And as general
question x.py and y.py)
How I can do it? Please consider this as a newbie question as well.

Thanks,
Senthil

Jul 11 '06 #1
9 2052
"Phoe6" <or*******@gmail.comwrote:
How do I compare the performance of pyConfig.py vs pyConparse.py using
timeit module?
$ python -m timeit -s "import pyConfig" "pyConfig.pyConfig()"
$ python -m timeit -s "import pyConparse" "pyConparse.pyConParse()"

note that timeit runs the benchmarked function multiple times, so you may want
to remove the print statements.

</F>

Jul 11 '06 #2
Fredrik Lundh wrote:
>
$ python -m timeit -s "import pyConfig" "pyConfig.pyConfig()"
$ python -m timeit -s "import pyConparse" "pyConparse.pyConParse()"
note that timeit runs the benchmarked function multiple times, so you may want
to remove the print statements.
Thanks a lot Fredrik!. I did not know that timeit runs benchmarked
function multiple times. I got scared with multiple prints and thought
import pyConfig has put it in infinite loop and I had killed the
program.

I could use Timer function as well.

Thanks,
Senthil

Jul 11 '06 #3
"Phoe6"
>$ python -m timeit -s "import pyConfig" "pyConfig.pyConfig()"
$ python -m timeit -s "import pyConparse" "pyConparse.pyConParse()"
>note that timeit runs the benchmarked function multiple times, so you may want
to remove the print statements.

Thanks a lot Fredrik!. I did not know that timeit runs benchmarked
function multiple times. I got scared with multiple prints and thought
import pyConfig has put it in infinite loop and I had killed the
program.

I could use Timer function as well.
for cases like this, the command form gives a better result with less effort; it picks
a suitable number of iterations based on how fast the code actually runs, instead of
using a fixed number, and it also runs the test multiple times, and picks the smallest
observed time.

</F>

Jul 11 '06 #4

"Fredrik Lundh" <fr*****@pythonware.comwrote in message
news:ma***************************************@pyt hon.org...
$ python -m timeit -s "import pyConfig" "pyConfig.pyConfig()"
$ python -m timeit -s "import pyConparse" "pyConparse.pyConParse()"

note that timeit runs the benchmarked function multiple times, so you may
want
to remove the print statements.
Hello,
Could you tell me what the "-m" switch does or even better, where to find
information on all switches in the documentation? Thanks.
Louis
Jul 11 '06 #5
On 12/07/2006 1:33 AM, Phoe6 wrote:
Hi,
Hi,

I'm a little astonished that anyone would worry too much (if at all!)
about how long it took to read a config file. Generally, one would
concentrate on correctness, and legibility of source code. There's not
much point IMHO in timing your pyConfig.py in its current form. Please
consider the following interspersed comments.

Also, the functionality of the two modules that you are comparing is
somewhat different ;-)

Cheers,
John

Following are my files.
----

pyConfig.py
----
import re

def pyConfig():
fhandle = open( 'config1.txt', 'r' )
arr = fhandle.readlines()
fhandle.close()

hash = {}

for item in arr:
There is no need of readlines(). Use:

for item in fhandle:
txt = item.strip()
str.strip() removes leading and trailing whitespace. Hence if the line
is visually empty, txt will be "" i.e. a zero-length string.
if re.search( '^\s*$', txt ):
For a start, your regex is constrained by the ^ and $ to matching a
whole string, so you should use re.match, not re.search. Read the
section on this topic in the re manual. Note that re.search is *not*
smart enough to give up if the test at the beginning fails. Second
problem: you don't need re at all! Your regex says "whole string is
whitespace", but the strip() will have reduced that to an empty string.
All you need do is:

if not txt: # empty line
continue
if re.search( '^#.*$', txt ):
Similar to the above. All you need is:

if txt.startswith('#'): # line is comment only
or (faster but less explicit):
if txt[0] == '#': # line is comment only
continue
if not re.search( '^\s*(\w|\W)+\s*=\s*(\w|\W)+\s*$', txt ):
(1) search -match, lose the ^
(2) lose the first and last \s* -- strip() means they are redundant.
(3) What are you trying to achieve with (\w|\W) ??? Where I come from,
"select things that are X or not X" means "select everything". So the
regex matches 'anything optional_whitespace = optional_whitespace
anything'. However 'anything' includes whitespace. You probably intended
something like 'word optional_whitespace = optional_whitespace
at_least_1_non-whitespace':

if not re.match('\w+\s*=\s*\S+.*$'):
but once you've found a non-whitespace after the =, it's pointless
continuing, so:
if not re.match('\w+\s*=\s*\S'):
continue
Are you sure such lines can be silently ignored? Might they be errors?
hash[txt.split( '=' )[0].strip().lower()] = txt.split( '='
)[1].strip()
Best to avoid splitting twice. Also it's a little convoluted. Also
beware of multiple '=' in the line.

left, right = txt.split('=', 1)
key = left.strip().lower()
if key in hash:
# does this matter?
value = right.strip()
hash[key] = value
>
print hash['dbrepository']
----
Oh, yeah, that hash thing, regexes everywhere ... it's left me wondering
could this possibly be a translation of a script from another language :-)

Jul 11 '06 #6
On 12/07/2006 6:35 AM, 3c273 wrote:
"Fredrik Lundh" <fr*****@pythonware.comwrote in message
news:ma***************************************@pyt hon.org...
>$ python -m timeit -s "import pyConfig" "pyConfig.pyConfig()"
$ python -m timeit -s "import pyConparse" "pyConparse.pyConParse()"

note that timeit runs the benchmarked function multiple times, so you may
want
>to remove the print statements.

Hello,
Could you tell me what the "-m" switch does or even better, where to find
information on all switches in the documentation? Thanks.
Louis
You appear to know what a switch is. I'm therefore surprised that you
appear not to
know that the convention is that any program that uses
command-line switches should do something informative when run with a -h
switch.

HTH [NPI],
John
Jul 11 '06 #7

"John Machin" <sj******@lexicon.netwrote in message
news:44********@news.eftel.com...
You appear to know what a switch is. I'm therefore surprised that you
appear not to
know that the convention is that any program that uses
command-line switches should do something informative when run with a -h
switch.
Doh! Me thinks Windows at work "python /?" (No good!), Linux at home
"python -h" (Ah ha!). I still think it should be in the docs somewhere.
Thanks.
Louis
Jul 11 '06 #8
"3c273" wrote:
Doh! Me thinks Windows at work "python /?" (No good!)
that was supposed to be fixed in 2.5, but it doesn't seem to have made it into
beta 2. hmm.

</F>

Jul 12 '06 #9
3c273 wrote:
"John Machin" <sj******@lexicon.netwrote in message
news:44********@news.eftel.com...
>You appear to know what a switch is. I'm therefore surprised that you
appear not to
know that the convention is that any program that uses
command-line switches should do something informative when run with a -h
switch.
Doh! Me thinks Windows at work "python /?" (No good!), Linux at home
"python -h" (Ah ha!). I still think it should be in the docs somewhere.
python /? now works in 2.5 SVN.

Georg
Jul 12 '06 #10

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

Similar topics

1
by: Dennis Benzinger | last post by:
I just played around with the new timeit module. Using the following code I get some strange results: import timeit def test(s): result = 0 for c in s: result += ord(c) return result
2
by: Roy Smith | last post by:
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()
2
by: Aggelos I. Orfanakos | last post by:
Hello. Under Gentoo Linux, I issue: $ python timeit.py python: can't open file 'timeit.py' $ ls -al /usr/lib/python2.3/timeit.py -rw-r--r-- 1 root root 9833 Oct 19 02:17...
5
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...
5
by: rurpy | last post by:
Why doesn't the following work? It generates a "NameError: global name 'data' is not defined" error. import timeit global data data = env = "global data; x = data"
2
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 =...
2
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...
3
by: silverburgh.meryl | last post by:
Hi, I have a function in my python like this: def callFunc(line, no): # some code And I want to do a performance test like this: for line in f: for i in range(int(count)): t1 =...
7
by: ssecorp | last post by:
I am not clear about the results here. from timeit import Timer import Decorators def fib(n): a, b = 1, 0 while n: a, b, n = b, a+b, n-1
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
0
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...
0
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...

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.