Python从int到string的快速转换

Python从int到string的快速转换,python,string,python-2.7,type-conversion,converter,Python,String,Python 2.7,Type Conversion,Converter,我正在用python解决大量的阶乘问题,并且发现当我计算完阶乘后,转换为字符串以保存到文件需要相同的时间。我试图找到一种将int转换为string的快速方法。我将举一个计算和int转换时间的例子。我使用的是通用的a=str(a),但我觉得有更好的方法,比如使用缓冲区或库 例: 求解100000阶乘=456574个数集 计算时间:6.36秒 转换时间:5.20秒 如果您有任何问题/解决方案,请告诉我!什么都可以 import time factorial = 1 print(" ") one

我正在用python解决大量的阶乘问题,并且发现当我计算完阶乘后,转换为字符串以保存到文件需要相同的时间。我试图找到一种将int转换为string的快速方法。我将举一个计算和int转换时间的例子。我使用的是通用的a=str(a),但我觉得有更好的方法,比如使用缓冲区或库

例:

求解100000阶乘=456574个数集

计算时间:6.36秒

转换时间:5.20秒

如果您有任何问题/解决方案,请告诉我!什么都可以

import time

factorial = 1

print(" ")

one = int(input("lower  = "))
two = int(input("higher = "))

start = time.time()

for x in range(one,two + 1):
        factorial = factorial * two
        two = two - 1

end = time.time()

print("DONE! ")
print(end - start, "Seconds to compute")

start = time.time()

factorial = str(factorial)

f = open('Ans_1.txt','w')
f.write(factorial)
f.close()

end = time.time()

print(end - start, "Seconds to convert and save")

print(len(factorial), "Digets")
你可以试试x位数([base])

以上测试输出:

1.0336394309997559 Python转换时间

0.03306150436401367 gmpy2转换时间

此代码更快(但还不够!:D)

结果: 不管怎样,我认为使用多线程可以更快地完成

导入时间 输入数学 导入线程

res_dict = {}

def int_str(threadID, each_thread, max_thread):
    if threadID == 1 :
        res_dict[threadID] = (str(factorial // 10 ** (each_thread * (max_thread - 1))))
    elif threadID == max_thread:
        res_dict[threadID] = (str(int(factorial % 10 ** (each_thread * 1))))
    else: 
        tmp = (factorial % 10 ** (each_thread * (max_thread - threadID + 1))) // 10 ** (each_thread * (max_thread - threadID))
        pre = "0" * ((digits // max_thread) - (math.floor(math.log10(tmp))+1))
        res_dict[threadID] = (pre + str(int(tmp)))

factorial = 1

print(" ")

def fact(a,b):
    if b == 1:
        return 1
    else:
        return a * fact(a,b-1)

one = int(input("lower  = "))
two = int(input("higher = "))

start = time.time()

for x in range(one,two + 1):
        factorial = factorial * two
        two = two - 1

end = time.time()

print("DONE! ")
print(end - start, "Seconds to compute")


start = time.time()

digits = math.floor(math.log10(factorial))+1

max_thread      = 3
each_thread     = digits // max_thread

tr = []

for item in range(1, max_thread + 1):
    t = threading.Thread(target=int_str, args=(item, each_thread, max_thread))
    t.start()
    tr.append(t)


for item in tr:
    item.join()

last_res = ''

for item in sorted(res_dict):
    if item != max_thread:
        last_res += res_dict[item]
    else:
        last_res += ("0" * (digits - len(last_res) - len(res_dict[item]))) + res_dict[item]


f = open('Ans_2.txt','w')
f.write(last_res)
f.close()


end = time.time()
print(end - start, "Seconds to convert and save")

print(digits, "Digets")
更新: 只需使用
pypy
运行您的代码,速度惊人

╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║   ║ Count      ║ Compute(s)  ║  Convert(s)  ║ pypy Convert(s)   ║
╠═══╬════════════╬═════════════╬══════════════╬═══════════════════╣
║ 1 ║ 100,000    ║    2.98     ║     3.85     ║        0.79       ║
║ 2 ║ 250,000    ║   25.83     ║     39.83    ║        7.17       ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝

我们也需要看看你的代码。考虑将
int
转换为
str
<代码>str(int)是最快的。但你的阶乘肯定有改进的地方logic@MoinuddinQuadri我不确定他的阶乘逻辑能改进多少。我使用
math.factorial(100000)
获得了类似的运行时。如果OP使用
math.factorial
,那么我怀疑Python 2.7中是否可以做任何事情。在Python3中,它将相对更快。这里的讨论可能很有趣,但我不认为有更快的方法将其保存为字符串,因为这是一种内置的方法@chrisz:
math.factorial(100000)
比在Python3中使用此代码快20倍左右。我已经尝试了30多种不同的算法,试图比过去的
math
更快地计算时间,但最终还是放弃了。如果OP想让这段代码更快,我建议尽量将涉及大数字的步骤减到最少。存储大的数字需要更多的时间来存储小的数字。只需尝试pypy:D
gmpy2
也有一个非常快速的阶乘函数。在我的计算机上,
str(math.factorial(100000))
需要约2.5秒<代码>str(gmpy2.fac(100000))只需要约0.03秒。而
str(gmpy2.fac(1000000))
需要约0.7秒。
res_dict = {}

def int_str(threadID, each_thread, max_thread):
    if threadID == 1 :
        res_dict[threadID] = (str(factorial // 10 ** (each_thread * (max_thread - 1))))
    elif threadID == max_thread:
        res_dict[threadID] = (str(int(factorial % 10 ** (each_thread * 1))))
    else: 
        tmp = (factorial % 10 ** (each_thread * (max_thread - threadID + 1))) // 10 ** (each_thread * (max_thread - threadID))
        pre = "0" * ((digits // max_thread) - (math.floor(math.log10(tmp))+1))
        res_dict[threadID] = (pre + str(int(tmp)))

factorial = 1

print(" ")

def fact(a,b):
    if b == 1:
        return 1
    else:
        return a * fact(a,b-1)

one = int(input("lower  = "))
two = int(input("higher = "))

start = time.time()

for x in range(one,two + 1):
        factorial = factorial * two
        two = two - 1

end = time.time()

print("DONE! ")
print(end - start, "Seconds to compute")


start = time.time()

digits = math.floor(math.log10(factorial))+1

max_thread      = 3
each_thread     = digits // max_thread

tr = []

for item in range(1, max_thread + 1):
    t = threading.Thread(target=int_str, args=(item, each_thread, max_thread))
    t.start()
    tr.append(t)


for item in tr:
    item.join()

last_res = ''

for item in sorted(res_dict):
    if item != max_thread:
        last_res += res_dict[item]
    else:
        last_res += ("0" * (digits - len(last_res) - len(res_dict[item]))) + res_dict[item]


f = open('Ans_2.txt','w')
f.write(last_res)
f.close()


end = time.time()
print(end - start, "Seconds to convert and save")

print(digits, "Digets")
╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║   ║ Count      ║ Compute(s)  ║  Convert(s)  ║ pypy Convert(s)   ║
╠═══╬════════════╬═════════════╬══════════════╬═══════════════════╣
║ 1 ║ 100,000    ║    2.98     ║     3.85     ║        0.79       ║
║ 2 ║ 250,000    ║   25.83     ║     39.83    ║        7.17       ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝