2

我想知道哪个在性能方面更好:带有状态的“常规”python 函数,或生成器。与类似问题不同,我使用最简化的函数来隔离问题:

常规功能:

 >>> def counter_reg():
         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

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

在这两种情况下,调用counter()andcounter_reg()将产生相同的输出。

哪一个在性能方面更好?谢谢,

4

1 回答 1

5

以下是如何使用timeit 模块对 Python 函数进行基准测试的示例:

测试.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)]    

像这样运行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

要进行更彻底的基准测试,请尝试不同的 值N,但在这种情况下,我认为这无关紧要。

因此,正如您所料, usingitertools.countcount_regularor更快counter_gen

于 2013-06-01T09:30:15.467 回答