python实现计时器

import time


class Timer:
    def __init__(self, func=time.perf_counter):
        self.elapsed = 0.0
        self._func = func
        self._start = None

    def start(self):
        if self._start is not None:
            raise RuntimeError('Already started')
        self._start = self._func()

    def stop(self):
        if self._start is None:
            raise RuntimeError('Not started')
        end = self._func()
        self.elapsed += end - self._start
        self._start = None

    def reset(self):
        self.elapsed = 0.0

    def get_elapsed(self):
        if self._start is None:
            return 0.0
        self.stop()
        elapsed = self.elapsed
        self.start()
        return round(elapsed, 2)


    @property
    def running(self):
        return self._start is not None

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self.stop()

  

posted @ 2022-10-18 16:52  老鲜肉  阅读(99)  评论(0编辑  收藏  举报