1# Copyright (c) 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import logging
6import time
7
8
9class TimeProfile(object):
10  """Class for simple profiling of action, with logging of cost."""
11
12  def __init__(self, description='operation'):
13    self._starttime = None
14    self._endtime = None
15    self._description = description
16    self.Start()
17
18  def Start(self):
19    self._starttime = time.time()
20    self._endtime = None
21
22  def GetDelta(self):
23    """Returns the rounded delta.
24
25    Also stops the timer if Stop() has not already been called.
26    """
27    if self._endtime is None:
28      self.Stop(log=False)
29    delta = self._endtime - self._starttime
30    delta = round(delta, 2) if delta < 10 else round(delta, 1)
31    return delta
32
33  def LogResult(self):
34    """Logs the result."""
35    logging.info('%s seconds to perform %s', self.GetDelta(), self._description)
36
37  def Stop(self, log=True):
38    """Stop profiling.
39
40    Args:
41      log: Log the delta (defaults to true).
42    """
43    self._endtime = time.time()
44    if log:
45      self.LogResult()
46