Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python性能-函数与生成器函数_Python_Performance - Fatal编程技术网

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

python性能-函数与生成器函数,python,performance,Python,Performance,我想知道哪一个性能更好:带状态的“常规”python函数,还是生成器。与此不同,我使用最简化的函数来隔离问题: 常规功能: >>> def counter_reg(): if not hasattr(count_regular,"c"): count_regular.c = -1 count_regular.c +=1 return count_regular.c 发电机功能: >>

我想知道哪一个性能更好:带状态的“常规”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
% 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
在这两种情况下,调用
counter()
counter\u reg()
将产生相同的输出

哪一个性能更好?
谢谢,

下面是一个示例,说明如何使用以下工具对Python函数进行基准测试:

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)]    

像这样运行python来计时函数:

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

>>> counter = counter_gen()
>>> counter = counter.next
% 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
,尽管在这种情况下,我认为这无关紧要


因此,正如您所期望的那样,使用
itertools.count
count\u regular
counter\u gen

都要快,仅通过查看第一个函数,我不建议这样做。至少用
\uuu iter\uuuu
定义一个类,或者如果您需要将它作为一个函数,则使用一个默认参数
def counter\u reg(c=[-1])
并修改
counter\u gen()
每次调用它时都会生成一个新的计数器,
counter\u reg()
增加一个全局值(尽管该函数有名称空间)。差别很大。你可以自己用
timeit
模块来计时。更好地优化可读性。我怀疑发电机性能是瓶颈。(如果是,您可能不应该使用Python。)