OLD | NEW |
1 # Copyright (c) 2013 The Chromium Authors. All rights reserved. | 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 | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 import logging | 5 import logging |
6 import time | 6 import time |
7 | 7 |
8 | 8 |
9 class TimeProfile(object): | 9 class TimeProfile(object): |
10 """Class for simple profiling of action, with logging of cost.""" | 10 """Class for simple profiling of action, with logging of cost.""" |
11 | 11 |
12 def __init__(self, description): | 12 def __init__(self, description='operation'): |
13 self._starttime = None | 13 self._starttime = None |
| 14 self._endtime = None |
14 self._description = description | 15 self._description = description |
15 self.Start() | 16 self.Start() |
16 | 17 |
17 def Start(self): | 18 def Start(self): |
18 self._starttime = time.time() | 19 self._starttime = time.time() |
| 20 self._endtime = None |
19 | 21 |
20 def Stop(self): | 22 def GetDelta(self): |
21 """Stop profiling and dump a log.""" | 23 """Returns the rounded delta. |
22 if self._starttime: | 24 |
23 stoptime = time.time() | 25 Also stops the timer if Stop() has not already been called. |
24 logging.info('%fsec to perform %s', | 26 """ |
25 stoptime - self._starttime, self._description) | 27 if self._endtime is None: |
26 self._starttime = 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() |
OLD | NEW |