3 回答
TA贡献1828条经验 获得超13个赞
调整项
值得为sdolan的时间计算提供基准基准/调整,以显示“反转”的性能,而无需经常进行不必要的list()转换。此list()操作为运行时增加了26个usecs,仅在迭代器不可接受的情况下才需要此操作。
结果:
reversed(lst) -- 11.2 usecs
list(reversed(lst)) -- 37.1 usecs
lst[::-1] -- 23.6 usecs
计算:
# I ran this set of 100000 and came up with 11.2, twice:
python -m timeit "ol = [1, 2, 3]*1000; nl = reversed(ol)"
100000 loops, best of 3: 11.2 usec per loop
# This shows the overhead of list()
python -m timeit "ol = [1, 2, 3]*1000; nl = list(reversed(ol))"
10000 loops, best of 3: 37.1 usec per loop
# This is the result for reverse via -1 step slices
python -m timeit "ol = [1, 2, 3]*1000;nl = ol[::-1]"
10000 loops, best of 3: 23.6 usec per loop
结论:
这些测试的结论reversed()比[::-1]12.4 usecs 的切片速度更快
添加回答
举报