Created
October 17, 2017 04:10
-
-
Save qfgaohao/3ed7d332b5d4b8a5d79c610a69f261f5 to your computer and use it in GitHub Desktop.
A simple Timer.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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