python - 为什么 count() 方法比 for 循环 python 更快

标签 python

这里有 2 个函数做同样的事情,但是有谁知道为什么使用 count() 方法的函数比另一个快得多? (我的意思是它是如何工作的?它是如何构建的?)

如果可能的话,我想要一个比这里找到的更容易理解的答案:Algorithm used to implement the Python str.count function 或者源代码中有什么:https://hg.python.org/cpython/file/tip/Objects/stringlib/fastsearch.h

def scoring1(seq):
    score = 0
    for i in range(len(seq)):
       if seq[i] == '0':
           score += 1      
    return score

def scoring2(seq):
    score = 0
    score = seq.count('0') 
    return score

seq = 'AATTGGCCGGGGAG0CTTC0CTCC000TTTCCCCGGAAA'
# takes 1min15 when applied to 100 sequences larger than 100 000 characters
score1  = scoring1(seq)
# takes 10 sec when applied to 100 sequences larger than 100 000 characters
score2  = scoring2(seq)

非常感谢您的回复

最佳答案

@CodeMonkey 已经给出了答案,但是注意到您的第一个函数可以改进以使其运行速度提高大约 20% 可能会很有趣:

import time, random

def scoring1(seq):
    score=0
    for i in range(len(seq)):
       if seq[i]=='0':
           score+=1      
    return score

def scoring2(seq):
    score=0
    for x in seq:
       score += (x =='0')    
    return score

def scoring3(seq):
    score = 0
    score = seq.count('0') 
    return score

def test(n):
    seq = ''.join(random.choice(['0','1']) for i in range(n))
    functions = [scoring1,scoring2,scoring3]
    for i,f in enumerate(functions):
        start = time.clock()
        s = f(seq)
        elapsed = time.clock() - start
        print('scoring' + str(i+1) + ': ' + str(s) + ' computed in ' + str(elapsed) + ' seconds')

test(10**7)       

典型输出:

scoring1: 5000742 computed in 0.9651326495293333 seconds
scoring2: 5000742 computed in 0.7998054195159483 seconds
scoring3: 5000742 computed in 0.03732172598339578 seconds

前两种方法都被内置的 count() 所震撼。

故事的寓意:当您使用已经优化的内置方法时,您需要优化自己的代码。

关于python - 为什么 count() 方法比 for 循环 python 更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995614/

相关文章:

python - 使用 Python 连接 DataFrame 中的字段

python - 在postgresql中插入一个数组

python - Scipysolve_banded矩阵使用的求解方法

python - 测试Flask REST服务器

python - 根据 Pandas 中其他两列的比较将列设置为真/假?

python - Linregress 输出似乎不正确

python - python中小于2,000,000的素数之和

python - Hadoop 流 : PYTHONPATH not working when mapper runs

python - 在 django 项目中组织模板

python - SymPy 中的模 2 算术