Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

72 lines (53 sloc) 2.058 kb
# -*- coding: utf-8 -*-
"""
Ctimer - A timer context manager measuring the
wall time of the code block it contains.
*** Modified version by Ole Martin Bjørndalen (halloi),
with added features.
Copyright (C) 2013 Balthazar Rouberol - <brouberol@imap.cc>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from timeit import default_timer
class Timer(object):
""" A timer as a context manager. """
def __init__(self, timer=default_timer, factor=1):
self.timer = timer
self.factor = factor
self.start = self()
self.end = None
def __enter__(self):
""" Set start time """
self.start = self()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
""" Set end time """
self.end = self()
def reset(self):
""" Reset start time """
self.start = self()
def elapsed(self):
""" Return elapsed time since start """
if self.end is None:
return self() - self.start
else:
return self.end - self.start
def __call__(self):
""" Return the current time """
return self.timer() * self.factor
if __name__ == '__main__':
import time
# Count time in milliseconds
with Timer(factor=1000) as timer:
for _ in range(10):
print('{:.3} ms have passed so far.'.format(timer.elapsed())
time.sleep(0.1)
print('The loop took {:.3} ms.'.format(timer.elapsed())
Jump to Line
Something went wrong with that request. Please try again.