Skip to content

Instantly share code, notes, and snippets.

@bbjubjub2494
Created February 22, 2016 20:05
Show Gist options
  • Save bbjubjub2494/d9f19acbdfcd70a5b727 to your computer and use it in GitHub Desktop.
Save bbjubjub2494/d9f19acbdfcd70a5b727 to your computer and use it in GitHub Desktop.
# Copyright Lourkeur 2016
#
# This module defines the python class Chronometer.
#
# 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/>.
import time
import threading
class Chronometer:
'''Chronometers allow one to measure how much time an operation takes to
complete. Instances are throwaway. One just needs to enclose the timed
operation in a ``with`` block and then use ``getResult`` to obtain the
timing.
>>> c = Chronometer()
>>> with c:
... time.sleep(1)
>>> assert c.getResult() > 1
'''
def __init__(self):
self.c = threading.Condition()
self.r = None
def __enter__(self):
self.t1 = time.time()
def __exit__(self, *ign_err):
t2 = time.time()
with self.c:
self.r = t2 - self.t1
del self.t1
self.c.notify_all()
def getResult(self, timeout=None):
with self.c:
if self.c.wait_for(lambda: self.r != None, timeout):
return self.r
else:
raise Chronometer.NotFinished()
class NotFinished(BaseException):
'''This class is raised when the result is queried before the
timed operation finishes.
>>> c = Chronometer()
>>> with c:
... c.getResult(timeout = 0)
Traceback (most recent call last):
...
Chronometer.NotFinished
>>> c = Chronometer()
>>> c.getResult(timeout = 0)
Traceback (most recent call last):
...
Chronometer.NotFinished
'''
pass
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment