速度計測したかったので、時間を測るログクラスを用意することにしたけど、毎回呼ぶところを固定するのも面倒だったのでシングルトンがあるじゃん!ってことで試してみた。けど、理解するのなかなか難しかった…
環境
- Python 2.7.11
実装
# -*- coding:utf8 -*- from logging import getLogger import time logger = getLogger(__name__) class Singleton(type): def __call__(cls, *args, **kwargs): try: return cls.__instance except AttributeError: cls.__instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.__instance class SpeedChecker(object): __metaclass__ = Singleton def __init__(self): self.start_time_ms = time.time() def log_elapsed_time(self, comment=''): """速度を計測する. :type string: :param comment: 何かあれば :rtype: void :return: """ elapsed_time_ms = time.time() - self.start_time_ms logger.debug('elapsed_time: %f [sec] %s' % (elapsed_time_ms, comment))
参考
Python の メタプログラミング (__metaclass__, メタクラス) を理解する
ところで
PythonにはcProfileというモジュールがあるのでそれを使ったほうが早いですorz