Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7935587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T21:58:04+00:00 2026-06-03T21:58:04+00:00

I was fiddling around with Python’s generators and iterable class, just for fun. Basically

  • 0

I was fiddling around with Python’s generators and iterable class, just for fun. Basically I wanted test out something that I’ve never been too sure about: that classes in Pythons have some significant overhead and it’s better to rely on methods that implement yield instead of classes that implement an iterator protocol, if you can.

I couldn’t find a satisfying explanation on this topic in Google, so I decided to test them out on my own using these two simple scripts: func_iter.py and class_iter.py

Here’s func_iter.py:

#!/usr/bin/env python

import time  

x = 0
def create_generator(num):
    mylist = range(num)
    for i in mylist:
        yield i

t = time.time()
gen = create_generator(100000)

for i in gen:
    x = x + i

print "%.3f" % (time.time() - t)

And here’s class_iter.py:

#!/usr/bin/env python

import time

x = 0

class Generator(object):

    def __init__(self, num):
        self.start = 0
        self.end = num

    def __iter__(self):
        return self

    def next(self):
        if self.start == self.end:
            raise StopIteration
        else:
            self.start = self.start + 1
            return self.start

t = time.time()
gen = Generator(100000)

for i in gen:
    x = x + i

print "%.3f" % (time.time() - t)

I then ran each of them 10 times using this in bash (for class_iter.py, for example):

for i in {1..10}; do ./class_iter.py; done

And here are the average running times for each of them:

class_iter.py: 0.0864
func_iter.py: 0.0307

Now, my questions are:

  1. Are my methods correct? Is my comparison fair?
  2. If so, why the big difference? Why did class_iter.py take almost three times as long as func_iter.py to run?
  3. If not, how can I improve my methods or come up with a better comparison?

EDIT: As Dacav suggested, I also tried running func_iter.py using xrange instead of range. This decreases its average running time to 0.0263 seconds.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T21:58:07+00:00Added an answer on June 3, 2026 at 9:58 pm

    The class version spends lots of time accessing its own variables. Each self.whatever costs cycles. If you define your __iter__ as a generator and minimize the use of instance variables, the difference between class and function versions will be negligible:

    setup = """
    def create_generator(num):
        mylist = range(num)
        for i in mylist:
            yield i
    
    class Generator(object):
    
        def __init__(self, num):
            self.start = 0
            self.end = num
    
        def __iter__(self):
            return self
    
        def next(self):
            if self.start == self.end:
                raise StopIteration
            else:
                self.start = self.start + 1
                return self.start
    
    class Generator2(object):
    
        def __init__(self, num):
            self.mylist = range(num)
    
        def __iter__(self):
            for i in self.mylist:
                yield i
    """
    
    import timeit
    
    print timeit.timeit('for p in create_generator(1000):p', setup, number=1000)
    print timeit.timeit('for p in Generator(1000):p', setup, number=1000)
    print timeit.timeit('for p in Generator2(1000):p', setup, number=1000)
    

    Results:

    0.158941984177
    0.696810007095
    0.160784959793
    

    so the second generator class is almost as fast as the function version.

    Please do note that Generator and Generator2 in the example are not fully equivalent, there are cases when you cannot simply replace a “plain” iterator with a generator (e.g. marshaling).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm just fiddling around with user scripts in chrome right now, so please bear
Remember, this is using python. Well, I was fiddling around with an app I
I am fiddling around with .htaccess and mod_rewrite. I have a site that has
I've been fiddling around with drupal theming quite succesfully (or at least, that's what
Guys, good day. im starting to learn mysql and still fiddling around. I just
I am fiddling around with a dialog that pops up and displays an alarm
Quick question, hopefully I am just missing something simple. Ok I have one class
I'm fiddling around with creating sub queries just to become accustomed to them. I'm
I'm currently fiddling around with contenteditable=true to create a syntax highlighted input box. I'm
I'm using Visual Studio and while fiddling around with a custom control, I started

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.