• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
8time for the contained code.
9"""
10
11import sys
12import time
13
14
15def _indent(indent):
16    return '| ' * indent
17
18
19class 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('{} {} time taken: {:0.1f}s\n'.format(
40                indent, self.name, self.elapsed))
41            Timer.fn('{}\n'.format(_indent(Timer.indent - 1)))
42        Timer.indent -= 1
43
44    @property
45    def elapsed(self):
46        return self.now - self.start
47
48    @property
49    def now(self):
50        return time.time()
51