由于在选择最佳正确答案之前我无法入睡,因此除了@jonrsharpe 提供的脚本之外,我还使用两种不同的脚本测试了每个答案的性能。
这是我使用profile比较三种不同解决方案性能的代码:
import profile
arr='test 123456789014'
def jonrsharpe(index):
global arr
for c in range(1,100000,1):
a=arr[:-index if index else None]
def Cyber(index):
global arr
for c in range(1,100000,1):
a=arr[:len(arr)-index]
def shashank(index):
global arr
for c in range(1,100000,1):
a=arr[:-index or None]
def testf():
for index in (0,3,6,9):
jonrsharpe(index)
Cyber(index)
shashank(index)
if __name__ == '__main__':
profile.run("testf()")
这是输出:
ncalls tottime percall cumtime percall filename:lineno(function)
799992 1.629 0.000 1.629 0.000 :0(len)
12 0.021 0.002 0.021 0.002 :0(range)
1 0.006 0.006 0.006 0.006 :0(setprofile)
1 0.000 0.000 4.390 4.390 <string>:1(<module>)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 4.396 4.396 profile:0(testf())
4 2.114 0.529 3.750 0.937 test.py:12(Cyber)
4 0.307 0.077 0.313 0.078 test.py:19(shashank)
1 0.000 0.000 4.390 4.390 test.py:26(testf)
4 0.319 0.080 0.328 0.082 test.py:5(jonrsharpe)
另一种方法:
import time
if __name__ == '__main__':
arr = '01234567890123456789012345678901234567890123456789'#range(1000)
for x in (0, 10, 20, 30,40,49):
print 'index=',x
start=time.clock()
for count in range(1000000):
a=arr[:-x if x else None]
print 'jonrsharpe=',round(time.clock()-start,4)
start=time.clock()
for count in range(1000000):
a=arr[:len(arr)-x]
print 'Cyber =',round(time.clock()-start,4)
start=time.clock()
for count in range(1000000):
a=arr[:-x or None]
print 'shashank =',round(time.clock()-start,4)
输出:
index= 0
jonrsharpe= 0.4918
Cyber = 0.5341
shashank = 0.4269
index= 10
jonrsharpe= 0.4617
Cyber = 0.5334
shashank = 0.4105
index= 20
jonrsharpe= 0.4271
Cyber = 0.4562
shashank = 0.3493
index= 30
jonrsharpe= 0.4217
Cyber = 0.4548
shashank = 0.3264
index= 40
jonrsharpe= 0.4713
Cyber = 0.8488
shashank = 0.6458
index= 49
jonrsharpe= 0.6159
Cyber = 0.5663
shashank = 0.4312
由于我将使用这行代码无数次,因此性能非常重要,@Shashank 的解决方案在大多数情况下都是赢家,即使只是一点点。