列表中所有字符串的长度:最快的方式 [英] Length of all string in the list: the fastest way

查看:57
本文介绍了列表中所有字符串的长度:最快的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试:

python3 -m timeit -c 'len("".join([str(x) for x in range(0, 999999)]))'10 个循环,最好的 3 个:每个循环 330 毫秒python3 -m timeit -c 'sum((len(y) for y in [str(x) for x in range(0, 999999)]))10 个循环,最好的 3 个:每个循环 439 毫秒

为什么会这样?有没有更快的方法?

附言假设事先会有一个字符串列表.

解决方案

一个更好的 IPython 基准测试表明情况比你想象的要糟糕:

<预><代码>>>>lst = [str(x) for x in range(0, 999999)]>>>%timeit len("".join(lst))100 个循环,最好的 3 个:每个循环 9.94 毫秒>>>%timeit sum(len(x) for x in lst)10 个循环,最好的 3 个:每个循环 62.2 毫秒

您在这里看到了两个影响,Python 中函数调用的开销及其迭代的开销."".join 没有,因为它是在 C 中执行循环的单个方法调用.可以从 map 获得具有较少内存使用的中间性能:><预><代码>>>>%timeit sum(map(len, lst))10 个循环,最好的 3 个:每个循环 29.4 毫秒

I'm trying:

python3 -m timeit -c 'len("".join([str(x) for x in range(0, 999999)]))'
10 loops, best of 3: 330 msec per loop

python3 -m timeit -c 'sum((len(y) for y in [str(x) for x in range(0, 999999)]))
10 loops, best of 3: 439 msec per loop

Why does this happen? Is there a faster way?

P.S. It is assumed that a list of strings will be in advance.

解决方案

A better benchmark with IPython shows the situation is worse than you thought:

>>> lst = [str(x) for x in range(0, 999999)]
>>> %timeit len("".join(lst))
100 loops, best of 3: 9.94 ms per loop
>>> %timeit sum(len(x) for x in lst)
10 loops, best of 3: 62.2 ms per loop

You're seeing two effects here, the overhead of function calls in Python and the overhead of its iteration. "".join doesn't have either because it's a single method call that does a loop in C. Intermediate performance with less memory use can be gotten from map:

>>> %timeit sum(map(len, lst))
10 loops, best of 3: 29.4 ms per loop

这篇关于列表中所有字符串的长度:最快的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆