简体   繁体   English

python性能-函数与生成器函数

[英]python performance- function vs generator functions

I want to know which one is better in performance terms: a "regular" python function with state, or a generator. 我想知道哪个在性能方面更好:带状态的“常规” python函数或生成器。 Unlike similar questions , I'm using the most simplified function to isolate the problem: 类似的问题不同,我使用最简化的函数来隔离问题:

Regular function: 常规功能:

 >>> def counter_reg():
         if not hasattr(count_regular,"c"):
             count_regular.c = -1
         count_regular.c +=1
         return count_regular.c

Generator functions: 发电机功能:

>>> def counter_gen():
    c = 0
    while True:
        yield c
        c += 1

>>> counter = counter_gen()
>>> counter = counter.next

In both cases, calling counter() and counter_reg() will produce the same output. 在这两种情况下,调用counter()counter_reg()都会产生相同的输出。

Which one is better in terms of performance? 在性能方面哪个更好? Thanks, 谢谢,

Here is an example of how you can benchmark Python functions using the timeit module : 这是一个如何使用timeit模块对Python函数进行基准测试的示例:

test.py: test.py:

import itertools as IT

def count_regular():
     if not hasattr(count_regular,"c"):
         count_regular.c = -1
     count_regular.c +=1
     return count_regular.c

def counter_gen():
    c = 0
    while True:
        yield c
        c += 1

def using_count_regular(N):
    return [count_regular() for i in range(N)]

def using_counter_gen(N):
    counter = counter_gen()
    return [next(counter) for i in range(N)]    

def using_itertools(N):
    count = IT.count()
    return [next(count) for i in range(N)]    

Run python like this to time the functions: 像这样运行python来计时函数:

% python -mtimeit -s'import test as t' 't.using_count_regular(1000)'
1000 loops, best of 3: 336 usec per loop
% python -mtimeit -s'import test as t' 't.using_counter_gen(1000)'
10000 loops, best of 3: 172 usec per loop
% python -mtimeit -s'import test as t' 't.using_itertools(1000)'
10000 loops, best of 3: 105 usec per loop

For a more thorough benchmarking, try different values of N , though in this case I don't think it is going to matter. 为了更全面地进行基准测试,请尝试使用不同的N值,尽管在这种情况下,我认为这无关紧要。

So as you would expect, using itertools.count is faster than either count_regular or counter_gen . 如您所料,使用itertools.countcount_regularcounter_gen更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM