Skip to content

Instantly share code, notes, and snippets.

@qfgaohao
Created October 17, 2017 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qfgaohao/3ed7d332b5d4b8a5d79c610a69f261f5 to your computer and use it in GitHub Desktop.
Save qfgaohao/3ed7d332b5d4b8a5d79c610a69f261f5 to your computer and use it in GitHub Desktop.
A simple Timer.
from datetime import datetime
import json
class Timer:
def __init__(self, outputFile):
self.fout = open(outputFile, 'w')
self.cache = []
self.records = {}
def start(self, event="time"):
self.records[event] = datetime.now()
def stop(self, event='time'):
end = datetime.now()
start = self.records[event]
self.cache.append({
'event': event,
'start': start.isoformat(),
'end': end.isoformat(),
'elapsed': (end - start).total_seconds()
})
del self.records[event]
def flush(self):
for row in self.cache:
self.fout.write(json.dumps(row) + "\n")
self.fout.flush()
self.cache = []
def __del__(self):
self.flush()
self.fout.close()
timer = Timer("default-timer.json")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment