Python从int到字符串的快速转换 [英] Python Fast conversion from int to string

查看:95
本文介绍了Python从int到字符串的快速转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用python解决大量阶乘,并发现当我完成计算阶乘时,转换成字符串并保存到文件需要花费相同的时间.我试图找到一种将int转换为字符串的快速方法.我将举一个计算和int转换时间的例子.我使用的是泛型a = str(a),但是却发现有更好的方法,例如使用缓冲区或库.

I am solving massive factorials in python and have found that when I am done calculating the factorial it takes the same time to convert to string to save to a file. I have tried to find a fast way to convert an int to string. I will put an example of computation and int conversion time. I am using the generic a = str(a) but fell like there is a better way like using a buffer or library.

EX:

解决100,000个阶乘= 456,574 Digets

Solving 100,000 factorial = 456,574 Digets

计算时间:6.36秒

转换时间:5.20秒

如果您有任何阻塞/解决方案,请告诉我!一切都会有帮助的.

If you have any segestions / solutions let me know! Anything will help.

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")

推荐答案

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

This code is faster (but not enough! :D)

╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║   ║ Count      ║ Compute(s)  ║  Convert(s)  ║  M.T Convert(s)   ║
╠═══╬════════════╬═════════════╬══════════════╬═══════════════════╣
║ 1 ║ 100,000    ║    2.68     ║     3.85     ║        2.81       ║
║ 2 ║ 250,000    ║   21.17     ║     39.83    ║       21.09       ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝

无论如何,我认为您可以通过多线程来更快地完成它.

Anyway, I think you can do it faster with multi-threading.

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

import time import math import threading

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 运行您的代码,速度就非常快!

update:

just run your code with pypy it's amazingly fast!

╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║   ║ 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       ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝

这篇关于Python从int到字符串的快速转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆