我在CodingBat.com上解决了一个Python问题。我编写了以下代码,用于打印字符串n次的简单问题 -
def string_times(str, n):
return n * str
官方结果是 -
def string_times(str, n):
result = ""
for i in range(n):
result = result + str
return result
print string_times('hello',3)
两个功能的输出相同。我很好奇字符串乘法(第一个函数)如何在性能基础上对for循环(第二个函数)执行。我的意思是哪一个更快并且大多使用?
另外请建议我自己解决这个问题的方法(使用time.clock()或类似的东西)
答案 0 :(得分:7)
我们可以使用the timeit
module对此进行测试:
python -m timeit "100*'string'"
1000000 loops, best of 3: 0.222 usec per loop
python -m timeit "''.join(['string' for _ in range(100)])"
100000 loops, best of 3: 6.9 usec per loop
python -m timeit "result = ''" "for i in range(100):" " result = result + 'string'"
100000 loops, best of 3: 13.1 usec per loop
你可以看到乘法是更快的选择。您可以注意到,虽然字符串连接版本在CPython中不是那么糟糕,但may not be true in other versions of Python。出于这个原因,你应该总是选择字符串乘法或str.join()
- 不仅要考虑速度,还要考虑可读性和简洁性。
答案 1 :(得分:2)
您可以使用命令行或代码中的timeit内容来查看某些python代码的速度:
$ python -m timeit "\"something\" * 100"
1000000 loops, best of 3: 0.608 usec per loop
为您的其他功能执行类似操作并进行比较。
答案 2 :(得分:2)
我已经计划了以下三个功能:
def string_times_1(s, n):
return s * n
def string_times_2(s, n):
result = ""
for i in range(n):
result = result + s
return result
def string_times_3(s, n):
"".join(s for _ in range(n))
结果如下:
In [4]: %timeit string_times_1('hello', 10)
1000000 loops, best of 3: 262 ns per loop
In [5]: %timeit string_times_2('hello', 10)
1000000 loops, best of 3: 1.63 us per loop
In [6]: %timeit string_times_3('hello', 10)
100000 loops, best of 3: 3.87 us per loop
正如您所看到的,s * n
不仅是最清晰,最简洁的,而且也是最快的。