Skip to content

Instantly share code, notes, and snippets.

@naoyat
Last active April 4, 2017 04:40
Show Gist options
  • Save naoyat/ecec2314a52ae28c1eac8344f9305d0f to your computer and use it in GitHub Desktop.
Save naoyat/ecec2314a52ae28c1eac8344f9305d0f to your computer and use it in GitHub Desktop.
stopwatch - 時間計測用ツール
# -*- encoding: utf-8 -*-
"""
stopwatch.py
by naoya_t
```
from stopwatch import stopwatch
import time
with stopwatch('test stopwatch') as w:
time.sleep(1.0)
```
"""
import time
import sys
import traceback
import logging
_logger = logging.getLogger(__name__)
def _ansi_tag(num):
sys.stdout.write('\x1b[%dm' % num)
class stopwatch :
second = 1
millisecond = 1000
microsecond = 1000000
def __init__(self, title=None, unit=millisecond, logger=None):
if title is None:
self.title = u'%g' % time.time()
elif isinstance(title, unicode):
self.title = title
else:
self.title = title.decode('utf-8')
# self.icon = u'\u231a' # WATCH
# self.icon = u'\u231b ' # HOURGLASS
# self.icon = u'\u23f0 ' # ALARM CLOCK
self.icon = u'\u23f1 ' # STOPWATCH
self.unit = unit
# self.icon = u'\u23f2 ' # TIMER CLOCK
# self.icon = u'\u23f3 ' # HOURGLASS WITH FLOWING SAND
self.logger = logger
def __enter__(self):
self.T0 = time.time()
return self
def lapse(self):
# print "lapse", time.time() - self.T0
return time.time() - self.T0
def __exit__(self, exc_type, exc_value, exc_traceback):
if exc_type is not None:
if self.logger:
print exc_type, exc_value
traceback.print_tb(exc_traceback)
else:
_ansi_tag(31) # red
print exc_type, exc_value
traceback.print_tb(exc_traceback)
_ansi_tag(0) # reset
dt = self.lapse()
icon = self.icon.encode('utf-8')
title = self.title.encode('utf-8')
if self.unit == stopwatch.microsecond:
_unit_str = 'μs'
elif self.unit == stopwatch.millisecond:
_unit_str = 'ms'
elif self.unit == stopwatch.second:
_unit_str = 's'
else:
self.unit = stopwatch.second
_unit_str = 's'
_msg = '%s%-8s: %8.3f%s' % (icon, title, dt * self.unit, _unit_str)
if self.logger:
self.logger.info(_msg)
else:
_ansi_tag(36) # cyan
print _msg
_ansi_tag(0) # reset
return dt
if __name__ == '__main__':
with stopwatch('demo') as wt:
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment