473,568 Members | 2,762 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Method much slower than function?

Hi all,

I am running Python 2.5 on Feisty Ubuntu. I came across some code that
is substantially slower when in a method than in a function.

############### ## START SOURCE #############
# The function

def readgenome(file handle):
s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
s += line.strip()
return s

# The method in a class
class bar:
def readgenome(self , filehandle):
self.s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
self.s += line.strip()

############### ## END SOURCE ##############
When running the function and the method on a 20,000 line text file, I
get the following:
>>cProfile.run( "bar.readgenome (open('cb_foo') )")
20004 function calls in 10.214 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno (function)
1 0.000 0.000 10.214 10.214 <string>:1(<mod ule>)
1 10.205 10.205 10.214 10.214 reader.py:11(re adgenome)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profil er' objects}
19999 0.009 0.000 0.009 0.000 {method 'strip' of 'str'
objects}
1 0.000 0.000 0.000 0.000 {method 'xreadlines' of
'file' objects}
1 0.000 0.000 0.000 0.000 {open}

>>cProfile.run( "z=r.readgenome (open('cb_foo') )")
20004 function calls in 0.041 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno (function)
1 0.000 0.000 0.041 0.041 <string>:1(<mod ule>)
1 0.035 0.035 0.041 0.041 reader.py:2(rea dgenome)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profil er' objects}
19999 0.007 0.000 0.007 0.000 {method 'strip' of 'str'
objects}
1 0.000 0.000 0.000 0.000 {method 'xreadlines' of
'file' objects}
1 0.000 0.000 0.000 0.000 {open}
The method takes 10 seconds, the function call 0.041 seconds!

Yes, I know that I wrote the underlying code rather inefficiently, and
I can streamline it with a single file.read() call instead if an
xreadlines() + strip loop. Still, the differences in performance are
rather staggering! Any comments?

Thanks,

Iddo

Jun 14 '07 #1
27 1704
On 2007-06-14, id****@gmail.co m <id****@gmail.c omwrote:
Hi all,

I am running Python 2.5 on Feisty Ubuntu. I came across some code that
is substantially slower when in a method than in a function.

############### ## START SOURCE #############
# The function

def readgenome(file handle):
s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
s += line.strip()
return s

# The method in a class
class bar:
def readgenome(self , filehandle):
self.s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
self.s += line.strip()

############### ## END SOURCE ##############
When running the function and the method on a 20,000 line text file, I
get the following:
>>>cProfile.run ("bar.readgenom e(open('cb_foo' ))")
20004 function calls in 10.214 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno (function)
1 0.000 0.000 10.214 10.214 <string>:1(<mod ule>)
1 10.205 10.205 10.214 10.214 reader.py:11(re adgenome)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profil er' objects}
19999 0.009 0.000 0.009 0.000 {method 'strip' of 'str'
objects}
1 0.000 0.000 0.000 0.000 {method 'xreadlines' of
'file' objects}
1 0.000 0.000 0.000 0.000 {open}

>>>cProfile.run ("z=r.readgenom e(open('cb_foo' ))")
20004 function calls in 0.041 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall
filename:lineno (function)
1 0.000 0.000 0.041 0.041 <string>:1(<mod ule>)
1 0.035 0.035 0.041 0.041 reader.py:2(rea dgenome)
1 0.000 0.000 0.000 0.000 {method 'disable' of
'_lsprof.Profil er' objects}
19999 0.007 0.000 0.007 0.000 {method 'strip' of 'str'
objects}
1 0.000 0.000 0.000 0.000 {method 'xreadlines' of
'file' objects}
1 0.000 0.000 0.000 0.000 {open}
The method takes 10 seconds, the function call 0.041 seconds!

Yes, I know that I wrote the underlying code rather
inefficiently, and I can streamline it with a single
file.read() call instead if an xreadlines() + strip loop.
Still, the differences in performance are rather staggering!
Any comments?
It is likely the repeated attribute lookup, self.s, that's
slowing it down in comparison to the non-method version.

Try the following simple optimization, using a local variable
instead of an attribute to build up the result.

# The method in a class
class bar:
def readgenome(self , filehandle):
s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
s += line.strip()
self.s = s

To further speed things up, think about using the str.join idiom
instead of str.+=, and using a generator expression instead of an
explicit loop.

# The method in a class
class bar:
def readgenome(self , filehandle):
self.s = ''.join(line.st rip() for line in filehandle)

--
Neil Cerutti
Jun 14 '07 #2
En Wed, 13 Jun 2007 21:40:12 -0300, <id****@gmail.c omescribió:
Hi all,

I am running Python 2.5 on Feisty Ubuntu. I came across some code that
is substantially slower when in a method than in a function.

############### ## START SOURCE #############
# The function

def readgenome(file handle):
s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
s += line.strip()
return s

# The method in a class
class bar:
def readgenome(self , filehandle):
self.s = ''
for line in filehandle.xrea dlines():
if '>' in line:
continue
self.s += line.strip()
In the function above, s is a local variable, and accessing local
variables is very efficient (using an array of local variables, the
compiler assigns statically an index for each one).
Using self.s, on the other hand, requires a name lookup for each access.
The most obvious change would be to use a local variable s, and assign
self.s = s only at the end. This should make both methods almost identical
in performance.
In addition, += is rather inefficient for strings; the usual idiom is
using ''.join(items)
And since you have Python 2.5, you can use the file as its own iterator;
combining all this:

return ''.join(line.st rip() for line in filehandle if '>' not in line)

--
Gabriel Genellina

Jun 14 '07 #3
On 2007-06-14, id****@gmail.co m <id****@gmail.c omwrote:
The method takes 10 seconds, the function call 0.041 seconds!
What happens when you run them in the other order?

The first time you read the file, it has to read it from disk.
The second time, it's probably just reading from the buffer
cache in RAM.

--
Grant Edwards grante Yow! Catsup and Mustard
at all over the place! It's
visi.com the Human Hamburger!
Jun 14 '07 #4
Gabriel Genellina wrote:
In the function above, s is a local variable, and accessing local
variables is very efficient (using an array of local variables, the
compiler assigns statically an index for each one).
Using self.s, on the other hand, requires a name lookup for each access.
The most obvious change would be to use a local variable s, and assign
self.s = s only at the end. This should make both methods almost identical
in performance.
Yeah, that's a big deal and makes a significant difference on my
machine.
In addition, += is rather inefficient for strings; the usual idiom is
using ''.join(items)
Ehh. Python 2.5 (and probably some earlier versions) optimize += on
strings pretty well.

a=""
for i in xrange(100000):
a+="a"

and:

a=[]
for i in xrange(100000):
a.append("a")
a="".join(a)

take virtually the same amount of time on my machine (2.5), and the
non-join version is clearer, IMO. I'd still use join in case I wind
up running under an older Python, but it's probably not a big issue
here.
And since you have Python 2.5, you can use the file as its own iterator;
combining all this:

return ''.join(line.st rip() for line in filehandle if '>' not in line)
That's probably pretty good.

Jun 14 '07 #5
"sj*******@yaho o.com" <sj*******@yaho o.comwrites:
take virtually the same amount of time on my machine (2.5), and the
non-join version is clearer, IMO. I'd still use join in case I wind
up running under an older Python, but it's probably not a big issue here.
You should not rely on using 2.5 or even on that optimization staying in
CPython. Best is to use StringIO or something comparable.
Jun 14 '07 #6
En Thu, 14 Jun 2007 01:39:29 -0300, sj*******@yahoo .com
<sj*******@yaho o.comescribió:
Gabriel Genellina wrote:
>In addition, += is rather inefficient for strings; the usual idiom is
using ''.join(items)

Ehh. Python 2.5 (and probably some earlier versions) optimize += on
strings pretty well.

a=""
for i in xrange(100000):
a+="a"

and:

a=[]
for i in xrange(100000):
a.append("a")
a="".join(a)

take virtually the same amount of time on my machine (2.5), and the
non-join version is clearer, IMO. I'd still use join in case I wind
up running under an older Python, but it's probably not a big issue
here.
Yes, for concatenating a lot of a's, sure... Try again using strings
around the size of your expected lines - and make sure they are all
different too.

pyimport timeit
py>
pydef f1():
.... a=""
.... for i in xrange(100000):
.... a+=str(i)*20
....
pydef f2():
.... a=[]
.... for i in xrange(100000):
.... a.append(str(i) *20)
.... a="".join(a)
....
pyprint timeit.Timer("f 2()", "from __main__ import f2").repeat(num ber=1)
[0.4267366383157 6358, 0.4280759146763 0662, 0.4440148119383 8876]
pyprint timeit.Timer("f 1()", "from __main__ import f1").repeat(num ber=1)

....after a few minutes I aborted the process...

--
Gabriel Genellina

Jun 14 '07 #7
On Jun 13, 5:40 pm, ido...@gmail.co m wrote:
Hi all,

I am running Python 2.5 on Feisty Ubuntu. I came across some code that
is substantially slower when in a method than in a function.
>cProfile.run(" bar.readgenome( open('cb_foo')) ")

20004 function calls in 10.214 CPU seconds
>cProfile.run(" z=r.readgenome( open('cb_foo')) ")

20004 function calls in 0.041 CPU seconds
I suspect open files are cached so the second reader
picks up where the first one left: at the of the file.
The second call doesn't do any text processing at all.

-- Leo

Jun 14 '07 #8
Neil Cerutti a écrit :
(snip)
class bar:
def readgenome(self , filehandle):
self.s = ''.join(line.st rip() for line in filehandle)
=>
self.s = ''.join(line.st rip() for line in filehandle if not
'>' in line)
Jun 14 '07 #9
Gabriel Genellina wrote:
En Thu, 14 Jun 2007 01:39:29 -0300, sj*******@yahoo .com
<sj*******@yaho o.comescribió:
>Gabriel Genellina wrote:
>>In addition, += is rather inefficient for strings; the usual idiom is
using ''.join(items)

Ehh. Python 2.5 (and probably some earlier versions) optimize += on
strings pretty well.

a=""
for i in xrange(100000):
a+="a"

and:

a=[]
for i in xrange(100000):
a.append("a")
a="".join(a)

take virtually the same amount of time on my machine (2.5), and the
non-join version is clearer, IMO. I'd still use join in case I wind
up running under an older Python, but it's probably not a big issue
here.

Yes, for concatenating a lot of a's, sure... Try again using strings
around the size of your expected lines - and make sure they are all
different too.

pyimport timeit
py>
pydef f1():
... a=""
... for i in xrange(100000):
... a+=str(i)*20
...
pydef f2():
... a=[]
... for i in xrange(100000):
... a.append(str(i) *20)
... a="".join(a)
...
pyprint timeit.Timer("f 2()", "from __main__ import f2").repeat(num ber=1)
[0.4267366383157 6358, 0.4280759146763 0662, 0.4440148119383 8876]
pyprint timeit.Timer("f 1()", "from __main__ import f1").repeat(num ber=1)

...after a few minutes I aborted the process...
I can't confirm this.

$ cat join.py
def f1():
a = ""
for i in xrange(100000):
a += str(i)*20

def f2():
a = []
for i in xrange(100000):
a.append(str(i) *20)
a = "".join(a)

def f3():
a = []
append = a.append
for i in xrange(100000):
append(str(i)*2 0)
a = "".join(a)

$ python2.5 -m timeit -s 'from join import f1' 'f1()'
10 loops, best of 3: 212 msec per loop
$ python2.5 -m timeit -s 'from join import f2' 'f2()'
10 loops, best of 3: 259 msec per loop
$ python2.5 -m timeit -s 'from join import f3' 'f3()'
10 loops, best of 3: 236 msec per loop

Peter

Jun 14 '07 #10

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

Similar topics

18
3252
by: Karl Pech | last post by:
Hi, I got a task there I have to compute pi using the Method above. So I wrote the following program: --- import random import math
24
2836
by: el_roachmeister | last post by:
Is there a way to make a text link post to a form without passing all the parameters in the url? The urls tend to get very long and messy. I often wonder if there is a limit to how long they can get?
12
2438
by: Gustavo L. Fabro | last post by:
Greetings! Getting straight to the point, here are the results of my experiment. I've included my comments and questions after them. The timing: (The total time means the sum of each line's drawing time. Time is measured in clock ticks (from QueryPerformanceCounter() API). The processor resolution (QueryPerformanceFrequency()) for my
6
22500
by: Martin | last post by:
I'd like to be able to get the name of an object instance from within a call to a method of that same object. Is this at all possible? The example below works by passing in the name of the object instance (in this case 'myDog'). Of course it would be better if I could somehow know from within write() that the name of the object instance was...
2
1636
by: Russell Hind | last post by:
I have a delegate which I use to store a current 'state' function (for a statemachine inside a form). __delegate void State_t(const Message_c& Message); I assign to it such as m_State = new State_t(this, StateShutdown); How can I later check which method the State is pointing to? And is
12
1723
by: Tim Frawley | last post by:
I have a method for testing variable length strings for all digits: Dim ch As String Dim i As Integer AllDigits = True For i = 1 To Len(txt) ' See if the next character is a non-digit. ch = Mid$(txt, i, 1) If ch < "0" Or ch > "9" Then
77
5175
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
19
2419
by: zzw8206262001 | last post by:
Hi,I find a way to make javescript more like c++ or pyhon There is the sample code: function Father(self) //every contructor may have "self" argument { self=self?self:this; //every class may have this statement self.hello = function() {
8
1662
by: =?Utf-8?B?WVhR?= | last post by:
Hello, I used Image.FromFile method to get lots of images from files, it's very slow in Windows Vista, but it's fast in Windows XP! could anyone please tell how to speed in Windows Vista? thank you
0
7604
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7916
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. ...
0
8117
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...
1
7660
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...
0
6275
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...
1
5498
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...
0
3651
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...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1207
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.