I have the following type of code, but it is slow because report()
is called very often.
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)
In this illustrative code example, I would like the report to be up-to-date (at most 10s old), so I would like to throttle that function.
I could fork in report, write the current timestamp, and wait for that period, and check using a shared memory timestamp if report has been called in the meantime. If yes, terminate, if not, write the report.
Is there a more elegant way to do it in Python?
reporter
class), it might not take as long. – Mardenfor
loop, and then pass the opened file to thereport()
function as a second parameter. Then close the file after thefor
loop has ended. Though your wholereport()
function becomesdef report(f, values): f.write(str(values))
, and you might consider inlining it. No need to re-create thefile.write()
method :) – Transilluminate