【发布时间】:2015-04-09 19:52:47
【问题描述】:
我有一个非常长的字符串,几乎有 1 兆字节长,我需要将其写入文本文件。常规的
file = open("file.txt","w")
file.write(string)
file.close()
可以,但是太慢了,有什么方法可以让我写得更快吗?
我正在尝试将数百万位数字写入文本文件
编号为math.factorial(67867957)的顺序
这是分析中显示的内容:
203 function calls (198 primitive calls) in 0.001 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 re.py:217(compile)
1 0.000 0.000 0.000 0.000 re.py:273(_compile)
1 0.000 0.000 0.000 0.000 sre_compile.py:172(_compile_charset)
1 0.000 0.000 0.000 0.000 sre_compile.py:201(_optimize_charset)
4 0.000 0.000 0.000 0.000 sre_compile.py:25(_identityfunction)
3/1 0.000 0.000 0.000 0.000 sre_compile.py:33(_compile)
1 0.000 0.000 0.000 0.000 sre_compile.py:341(_compile_info)
2 0.000 0.000 0.000 0.000 sre_compile.py:442(isstring)
1 0.000 0.000 0.000 0.000 sre_compile.py:445(_code)
1 0.000 0.000 0.000 0.000 sre_compile.py:460(compile)
5 0.000 0.000 0.000 0.000 sre_parse.py:126(__len__)
12 0.000 0.000 0.000 0.000 sre_parse.py:130(__getitem__)
7 0.000 0.000 0.000 0.000 sre_parse.py:138(append)
3/1 0.000 0.000 0.000 0.000 sre_parse.py:140(getwidth)
1 0.000 0.000 0.000 0.000 sre_parse.py:178(__init__)
10 0.000 0.000 0.000 0.000 sre_parse.py:183(__next)
2 0.000 0.000 0.000 0.000 sre_parse.py:202(match)
8 0.000 0.000 0.000 0.000 sre_parse.py:208(get)
1 0.000 0.000 0.000 0.000 sre_parse.py:351(_parse_sub)
2 0.000 0.000 0.000 0.000 sre_parse.py:429(_parse)
1 0.000 0.000 0.000 0.000 sre_parse.py:67(__init__)
1 0.000 0.000 0.000 0.000 sre_parse.py:726(fix_flags)
1 0.000 0.000 0.000 0.000 sre_parse.py:738(parse)
3 0.000 0.000 0.000 0.000 sre_parse.py:90(__init__)
1 0.000 0.000 0.000 0.000 {built-in method compile}
1 0.001 0.001 0.001 0.001 {built-in method exec}
17 0.000 0.000 0.000 0.000 {built-in method isinstance}
39/38 0.000 0.000 0.000 0.000 {built-in method len}
2 0.000 0.000 0.000 0.000 {built-in method max}
8 0.000 0.000 0.000 0.000 {built-in method min}
6 0.000 0.000 0.000 0.000 {built-in method ord}
48 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5 0.000 0.000 0.000 0.000 {method 'find' of 'bytearray' objects}
1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
【问题讨论】:
-
兆字节不是“巨大的”。您确定您的磁盘可以比 python 写入更快吗?您能否提供一个独立的基准测试,例如
python3 -c'open('file', 'w').write("a"*1000000)'您的计算机上的时间是几点?期望的时间是什么时候? -
大声笑,写 1 MB 文件不可能需要几个小时......它应该最多需要几秒钟(这很慷慨)......正如@JFSebastian 提到的,请用一些简单的...
-
您的分析显示了什么? docs.python.org/2/library/profile.html
-
/usr/bin/time python -c'import gmpy2; open("/tmp/file", "w").write(str(gmpy2.fac(67867957)))'在我的机器上花费不到 10 分钟。/tmp/file包含 500M 位数字 -
正如@J.F.Sebastian 所回答的,基本问题是
str(long)具有二次运行时间。我有偏见,因为我维护gmpy2,但如果你打算处理如此庞大的数字,你真的应该使用'gmpy2. BTW, the current development version (2.1.x) includes theprimorial` 函数。gmpy2.primorial(67867957)大约需要 3.5 秒。
标签: python performance python-3.x file-io