Last active
January 27, 2019 00:01
-
-
Save crowsonkb/741ecebbc2eda6559b30757868a90d43 to your computer and use it in GitHub Desktop.
A with-statement context manager to benchmark code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""A with-statement context manager to benchmark code.""" | |
import time | |
__all__ = ['Benchmark'] | |
class Benchmark: | |
"""A with-statement context manager to benchmark code.""" | |
def __init__(self, timer=time.perf_counter): | |
"""Constructs a new :class:`Benchmark`. | |
Args: | |
timer (Callable[[], Union[float, int]]): The timer function to use. | |
""" | |
self.timer = timer | |
self.start = None | |
self.end = None | |
def __enter__(self): | |
self.start = self.timer() | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
self.end = self.timer() | |
def get(self): | |
"""Gets the time elapsed so far during the benchmark. | |
Returns: | |
Union[float, int]: The time elapsed so far during the benchmark. | |
""" | |
if not self.end: | |
return self.timer() - self.start | |
return self.end - self.start |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
"""Tests the benchmark module.""" | |
from benchmark import Benchmark | |
def main(): | |
"""The main function.""" | |
with Benchmark() as result: | |
pass | |
print('Elapsed: {:.3f}µs'.format(result.get() * 1e6)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment