| 1 |
# DExTer : Debugging Experience Tester |
| 2 |
# ~~~~~~ ~ ~~ ~ ~~ |
| 3 |
# |
| 4 |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 5 |
# See https://llvm.org/LICENSE.txt for license information. |
| 6 |
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 7 |
"""RAII-style timer class to be used with a 'with' statement to get wall clock |
| 8 |
time for the contained code. |
| 9 |
""" |
| 10 |
|
| 11 |
import sys |
| 12 |
import time |
| 13 |
|
| 14 |
|
| 15 |
def _indent(indent): |
| 16 |
return "| " * indent |
| 17 |
|
| 18 |
|
| 19 |
class Timer(object): |
| 20 |
fn = sys.stdout.write |
| 21 |
display = False |
| 22 |
indent = 0 |
| 23 |
|
| 24 |
def __init__(self, name=None): |
| 25 |
self.name = name |
| 26 |
self.start = self.now |
| 27 |
|
| 28 |
def __enter__(self): |
| 29 |
Timer.indent += 1 |
| 30 |
if Timer.display and self.name: |
| 31 |
indent = _indent(Timer.indent - 1) + " _" |
| 32 |
Timer.fn("{}\n".format(_indent(Timer.indent - 1))) |
| 33 |
Timer.fn("{} start {}\n".format(indent, self.name)) |
| 34 |
return self |
| 35 |
|
| 36 |
def __exit__(self, *args): |
| 37 |
if Timer.display and self.name: |
| 38 |
indent = _indent(Timer.indent - 1) + "|_" |
| 39 |
Timer.fn( |
| 40 |
"{} {} time taken: {:0.1f}s\n".format(indent, self.name, self.elapsed) |
| 41 |
) |
| 42 |
Timer.fn("{}\n".format(_indent(Timer.indent - 1))) |
| 43 |
Timer.indent -= 1 |
| 44 |
|
| 45 |
@property |
| 46 |
def elapsed(self): |
| 47 |
return self.now - self.start |
| 48 |
|
| 49 |
@property |
| 50 |
def now(self): |
| 51 |
return time.time() |