xref: /aosp_15_r20/external/angle/build/util/lib/proto/time_consumption.py (revision 8975f5c5ed3d1c378011245431ada316dfb6f244)
1#!/usr/bin/env vpython3
2
3# Copyright 2024 The Chromium Authors
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6""" A metric implementation to calculate the time consumption.
7
8Example:
9  with TimeConsumption('foo'):
10    do_something()
11"""
12
13import time
14
15from contextlib import AbstractContextManager
16
17from measure import Measure
18from test_script_metrics_pb2 import TestScriptMetric
19
20
21class TimeConsumption(AbstractContextManager, Measure):
22
23  def __init__(self, name: str) -> None:
24    self._name = name + ' (seconds)'
25    self._start = 0
26    self._end = 0
27
28  def __enter__(self) -> None:
29    self._start = time.time()
30
31  def __exit__(self, exc_type, exc_value, traceback) -> bool:
32    self._end = time.time()
33    # Do not suppress exceptions.
34    return False
35
36  def dump(self) -> TestScriptMetric:
37    result = TestScriptMetric()
38    result.name = self._name
39    result.value = (self._end - self._start)
40    return result
41