追加比整数慢于python中的字符串?

时间:2019-03-19 14:19:56

标签: python python-3.x append

我在寻找一种测量函数速度的方法时遇到了这段代码。

def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
     import timeit
     print(timeit.timeit("test()", setup="from __main__ import test"))

当我运行它时,它大约需要10秒钟,这对我来说很奇怪。我记得当我将100.000字符串附加到字符串中时,只需要0.06秒。为什么将100个整数附加到列表中需要10秒钟?这是我用来在列表中附加字符串的代码。

def wordlist1():
    fin = open("words.txt")
    word_list = []
    for line in fin:
        word = line.strip()
        word_list.append(word)
    return word_list

3 个答案:

答案 0 :(得分:1)

I think your problem is the usage of the timeit module. When not specified, the param number defaults to 1e6. So what you are effectively measuring is how long it would take to append a hundred numbers to an array 1e6 times.

To verify this, I used this code snippet:

import timeit

alist = list(range(100))

L = []

def test():
    for i in alist:
        L.append(i)

elapsed = timeit.timeit("test()", setup="from __main__ import test, alist, L", number=1000000)

print('average time elapsed', elapsed/1000000)

On my machine, I got the following result:

7.74517...e-06

I do not know how you measured the append function for your txt file, but you could try to test it the same way.

答案 1 :(得分:1)

如果使用iPython,则可以使用其%timeit魔术命令来更清晰地解释结果。

In [1]: def test():
   ...:     """Stupid test function"""
   ...:     L = []
   ...:     for i in range(100):
   ...:         L.append(i)
   ...:

In [2]: %timeit test()
7.12 µs ± 22.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

在这里,结果是每次test的每次呼叫平均为7.12微秒,并且平均计算了7组100,000次test的呼叫。这与DocDriven在his answer中报告的7.75微秒一致。

答案 2 :(得分:-1)

尝试这个

def test():

L = []

对于i范围为(100)

dataMerge()