【发布时间】:2015-11-02 13:31:10
【问题描述】:
我有以下类型的代码,但速度很慢,因为report() 经常被调用。
import time
import random
def report(values):
open('report.html', 'w').write(str(values))
values = []
for i in range(10000):
# some computation
r = random.random() / 100.
values.append(r)
time.sleep(r)
# report on the current status, but this should not slow things down
report(values)
在这个说明性代码示例中,我希望报告是最新的(最多 10 年代旧),所以我想限制该功能。
我可以在报告中分叉,写入当前时间戳,然后等待该时间段,然后使用共享内存时间戳检查是否同时调用了报告。如果是,终止,如果不是,写报告。
有没有更优雅的方式在 Python 中做到这一点?
【问题讨论】:
-
对共享队列使用线程?
-
我想它很慢,因为你每次都打开文件(也应该关闭)。如果您保持文件打开(将其传递到报告函数或创建
reporter类),则可能不会花费很长时间。 -
您打算每次都覆盖该文件?
-
@Trengot 说了什么。您应该在
for循环之外打开文件,然后将打开的文件作为第二个参数传递给report()函数。然后在for循环结束后关闭文件。虽然你的整个report()函数变成了def report(f, values): f.write(str(values)),你可能会考虑内联它。无需重新创建file.write()方法:) -
由于您只是向报告文件添加值并且从未更改,您可以通过以附加模式打开文件来将值附加到文件中吗?例如。您不需要每次都写入所有值,您可以每隔 N 个值附加到文件中。
标签: python throttling