473,695 Members | 1,815 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question: How efficient is using generators for coroutine-likeproblems?

As a side track of my latest investigations, I began to rely heavily
on generators for some stuff where I would previsouly use a more
conventional approach. Whenever I need to process a list, I'm tending
towards the use of generators. One good example is if I want to print
a report, or to work over a list with complex processing for each
item. In both cases, a simple list comprehension can't be used. The
conventional approach involves setting up a empty result list, looping
over the list while appending the result, and finally returning it.
For strings, it's something like this:

def myfunc(items):
result = []
result += ["Start of processing"]
for item in items:
# do some processing with item
...
result += [str(item)]
result += ["End of processing"]
return result

This code is not only ugly to read, but it's inefficient because of
the way list and string concatenations are handled. Other alternatives
involve adding directly to the string, or using CStringIO. But I think
you've got the point. Now, using generators, the function code gets
simpler:

def myfunc(items):
yield "Start of processing"
for item in items:
# do some processing with item
...
yield str(item)
yield "End of processing"

I can print the results either way:

a) for line in myfunc([...]): print line

b) print "\n".list(myfun c([...]))

And I have other advantages -- no concatenations in the function code,
and the list can be generated as needed. This has the potential to
make the system less resource intensive (specially for large lists)
and more responsive.

Now, just because I can do it does not mean it's a good idea :-) For
particular cases, a measurement can be done. But I'm curious about the
generic case. What is the performance penalty of using generators in
situations as the ones shown above?

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #1
3 1948
Carlos Ribeiro wrote:
Now, just because I can do it does not mean it's a good idea :-) For
particular cases, a measurement can be done. But I'm curious about the
generic case. What is the performance penalty of using generators in
situations as the ones shown above?


There shouldn't be a significant performance penalty, since
generators set up the stack frame when they are created and
reuse it, rather than creating a new one for each function
call. They allow you to restructure your code more cleanly
but without taking a big hit from extra function calls.

But if you're concerned, there's always the timeit module
to tell you exactly what you're facing...

-Peter
Jul 18 '05 #2
Carlos Ribeiro <ca********@gma il.com> wrote:
...
result += ["Start of processing"]
I would suggest result.append(' Start of processing'). As you're
concerned with performance, see...:

kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]' 'r+=["goo"]'
1000000 loops, best of 3: 1.45 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]' 'r.append("goo" )'
1000000 loops, best of 3: 0.953 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'r=[]; a=r.append' 'a("goo")'
1000000 loops, best of 3: 0.556 usec per loop

i.e. you can get result.append into a local once at the start and end up
almost 3 times faster than with your approach, but even without this
you're still gaining handsomely with good old result.append vs your
preferred approach (where a singleton list gets created each time).

Now, just because I can do it does not mean it's a good idea :-) For
particular cases, a measurement can be done. But I'm curious about the
generic case. What is the performance penalty of using generators in
situations as the ones shown above?


Sorry, there's no "generic case" that I can think of. Since
implementations of generators, list appends, etc, are allowed to change
and get optimized at any transition 2.3 -> 2.4 -> 2.5 -> ... I see even
conceptually no way to compare performance except on a specific case.

"Generally" I would expect: if you're just looping on the result, a
generator should _gain_ performance wrt making a list. Consider cr.py:

x = map(str, range(333))

def withapp(x=x):
result = []
a = result.append
for item in x: a(item)
return result

def withgen(x=x):
for item in x: yield item

kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' 'for x in
cr.withapp(): pass'
1000 loops, best of 3: 220 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'import cr' 'for x in
cr.withgen(): pass'
1000 loops, best of 3: 200 usec per loop

The difference is more pronounced in 2.3, with the generator clocking in
at 280 usec, the appends at 370 (anybody who's interested in speed has
hopefully already downloaded 2.4 and is busy trying it out -- I can't
see any reason why not... even though one obviously can't yet deliver to
customers stuff based on what's still an alpha release, of course, at
least one can TRY it and pine for its general speedups;-).

A join is different...:

kallisti:~/cb alex$ python2.4 timeit.py -s'import cr'
'"\n".join(cr.w ithgen())'
1000 loops, best of 3: 274 usec per loop
kallisti:~/cb alex$ python2.4 timeit.py -s'import cr'
'"\n".join(cr.w ithapp())'
1000 loops, best of 3: 225 usec per loop

(speed difference was less pronounced in 2.3, 360 vs 350). Yeah, I
know, it's not easy to conceptualize -- if looping is faster why is
joining slower? "Implementa tion details" of course, and just the kind
of thing that might change any time, if some nice free optimization can
be obtained hither or yon...!
Alex
Jul 18 '05 #3
On Sun, 26 Sep 2004 11:47:03 +0200, Alex Martelli <al*****@yahoo. com> wrote:
i.e. you can get result.append into a local once at the start and end up
almost 3 times faster than with your approach, but even without this
you're still gaining handsomely with good old result.append vs your
preferred approach (where a singleton list gets created each time).
Thanks for the info -- specially regarding the "a=result.appen d"
trick. It's a good one, and also helps to make the code less
cluttered.
Now, just because I can do it does not mean it's a good idea :-) For
particular cases, a measurement can be done. But I'm curious about the
generic case. What is the performance penalty of using generators in
situations as the ones shown above?


Sorry, there's no "generic case" that I can think of. Since
implementations of generators, list appends, etc, are allowed to change
and get optimized at any transition 2.3 -> 2.4 -> 2.5 -> ... I see even
conceptually no way to compare performance except on a specific case.

"Generally" I would expect: if you're just looping on the result, a
generator should _gain_ performance wrt making a list. Consider cr.py:


That's my basic assumption. BTW, I had an alternative idea. I really
don't need to use "\n".join() . All that I need is to concatenate the
strings yielded by the generator, and the strings themselves should
include the necessary linebreaks. I'm not a timeit wizard, and neither
is a slow Windows machine reliable enough for timing tight loops, but
anyway here are my results:

---- testgen.py ----
def mygen():
for x in range(100):
yield "%d: this is a test string.\n" % x

def test_genlist():
return "".join(list(my gen()))

def test_addstr():
result = ""
for x in range(40):
# there is no append method for strings :(
result = result + "%d: this is a test string.\n" % x
return result

def test_gen_addstr ():
result = ""
for x in mygen(): result = result + x
return result

I've added the "%" operator because most of the time we are going to
work with generated strings, not with constants, and I thought it
would give a better idea of the timing.
python c:\python23\lib \timeit.py -s"import timegen" "timegen.test_g enlist()" 1000 loops, best of 3: 698 usec per loop
python c:\python23\lib \timeit.py -s"import timegen" "timegen.test_a ddstr()" 1000 loops, best of 3: 766 usec per loop
python c:\python23\lib \timeit.py -s"import timegen" "timegen.test_g en_addstr()" 1000 loops, best of 3: 854 usec per loop

The test has shown that adding strings manually is just a tad slower
than joining. But then I've decided to simplify my tests, and to add
small constant strings. The results have surprised me:

---- testgen2.py ----
def mygen():
for x in range(100):
yield "."

def test_genlist():
return "".join(list(my gen()))

def test_addstr():
result = ""
for x in range(100):
# there is no append method for strings :(
result = result + "."
return result

def test_gen_addstr ():
result = ""
for x in mygen(): result = result + x
return result
python c:\python23\lib \timeit.py -s"import timegen2" "timegen2.test_ genlist()" 1000 loops, best of 3: 368 usec per loop
python c:\python23\lib \timeit.py -s"import timegen2" "timegen2.test_ addstr()" 1000 loops, best of 3: 263 usec per loop
python c:\python23\lib \timeit.py -s"import timegen2" "timegen2.test_ gen_addstr()"
1000 loops, best of 3: 385 usec per loop

Now, it turns out that for this case, adding strings was *faster* than
joining lines. But in all cases, the generator was slower than adding
strings.

Up to this point, the answer to my question is: generators _have_ a
measurable performance penalty, and using a generator to return text
line by line to append later is slower than appending to the return
string line by line. But also, the difference between testbeds 1 and 2
show that this is not the dominating factor in performance -- simply
adding some string manipulation made the test run much slower.
Finally, I *haven't* done any testing using 2.4, though, and
generators are supposed to perform better with 2.4.

.... and I was about to finish it here, but I decided to check another thing.

There's still a catch. Generators were slower, because there is a
implicit function call whenever a new value is requested. So I've
added a new test:

---- testgen2.py ----
def teststr():
return "."

def test_addstr_fun ccall():
result = ""
for x in range(100):
result = result + teststr()
return result
python c:\python23\lib \timeit.py -s"import timegen2"

"timegen2.test_ addstr_funccall ()"
1000 loops, best of 3: 436 usec per loop

In this case, the code was measurably _slower_ than the generator
version (435 vs 385), and both are adding strings. It only shows how
hard is to try to optimize stuff -- depending on details, answers can
be totally different.

My conclusion, as of now, is that using generators in templating
mechanisms is a valuable tool as far as readability is concerned, but
it should not be done solely because of performance concerns. It may
be faster in some cases, but it's slower in the simplest situations.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmai l.com
mail: ca********@yaho o.com
Jul 18 '05 #4

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

Similar topics

4
3786
by: The_Incubator | last post by:
As the subject suggests, I am interested in using Python as a scripting language for a game that is primarily implemented in C++, and I am also interested in using generators in those scripts... Initially I was justing looking at using Python for some event scripting. So basically an event would trigger an object to run the appropriate Python script, which would be run in it's entirety and return control to the C++ code. After looking...
8
2254
by: Timothy Fitz | last post by:
It seems to me that in python, generators are not truly coroutines. I do not understand why. What I see is that generators are used almost exclusively for generation of lists just-in-time. Side effects are frowned upon. Coroutines, in contrast, are like split functions where side effects are often as important or more important than return values. I am currently writing a real time strategy game where I have visual effects and use...
8
2305
by: Paul Chiusano | last post by:
I've been playing around with generators and have run into a difficulty. Suppose I've defined a Node class like so: class Node: def __init__(self, data=None, left=None, right=None): self.children = self.children.append(left) self.children.append(right) self.data = data
15
2127
by: Jordan Rastrick | last post by:
First, a disclaimer. I am a second year Maths and Computer Science undergraduate, and this is my first time ever on Usenet (I guess I'm part of the http generation). On top of that, I have been using Python for a grand total of about a fortnight now. Hence, I apologise if what follows is a stupid suggestion, or if its already been made somewhere else, or if this is not the appropriate place to make it, etc. But I did honestly do some...
7
3924
by: Ioannis Vranos | last post by:
I want to create some random numbers for encryption purposes, and i wonder if the following scheme makes it more hard to guess the underneath number generation pattern, than the plain use of rand(): #include <cstdlib> #include <ctime> int GetRandomNumber()
58
30220
by: Larry David | last post by:
Ok, first of all, let's get the obvious stuff out of the way. I'm an idiot. So please indulge me for a moment. Consider it an act of "community service".... What does "64bit" mean to your friendly neighborhood C# programmer? The standard answer I get from computer sales people is: "It means that the CPU can process 64 bits of data at a time instead of 32." Ok... I guess I *kind* of understand what that means at an intuitive level, but what...
0
976
by: Calvin Spealman | last post by:
I was talking to some other people, who all were working on different schedulers and such for coroutines. We decided to work out a common API to give coroutines, and common rules to passing data between them, etc. I am wondering now if there is already work on this, or some schedulers I'm not aware of that have any deployment and a good, simple design. We also setup a group to discuss this and iron out our details and some common...
6
2310
by: George Trojan | last post by:
A while ago I found somewhere the following implementation of frange(): def frange(limit1, limit2 = None, increment = 1.): """ Range function that accepts floats (and integers). Usage: frange(-2, 2, 0.1) frange(10) frange(10, increment = 0.5) The returned value is an iterator. Use list(frange) for a list.
4
1262
by: ig | last post by:
First off, I'm a python n00b, so feel free to comment on anything if I'm doing it "the wrong way." I'm building a discrete event simulation tool. I wanted to use coroutines. However, I want to know if there's any way to hide a yield statement. I have a class that I'd like to look like this: class Pinger(Actor): def go(self): success = True
0
8623
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8565
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8977
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
8839
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,...
1
6488
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
4339
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
4577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2997
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
2269
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.