众所周知,重复的字符串连接效率很低,因为Python字符串是不可变的。我会去
strprime = str(prime)
以我的基准而言,这始终是最快的解决方案。这是我的小基准程序:
import decimaldef f1(x): ''' Definition by OP ''' strprime = "" while x > 0: strprime += str(x%10) x //= 10 return strprimedef digits(x): while x > 0: yield x % 10 x //= 10def f2(x): ''' Using string.join() to avoid repeated string concatenation ''' return "".join((chr(48 + d) for d in digits(x)))def f3(x): ''' Plain str() ''' return str(x)def f4(x): ''' Using Decimal class''' return decimal.Decimal(x).to_eng_string()x = 2**100if __name__ == '__main__': import timeit for i in range(1,5): funcName = "f" + str(i) print(funcName+ ": " + str(timeit.timeit(funcName + "(x)", setup="from __main__ import " + funcName + ", x")))
对我来说,这是打印的(使用Python 2.7.10):
f1: 15.3430171013f2: 20.8928260803f3: 0.310356140137f4: 2.80087995529
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)