Coverage for python/lsst/verify/timer.py: 52%

19 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-05-04 02:34 -0700

1# This file is part of verify. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22__all__ = ["time_this_to_measurement"] 

23 

24from contextlib import contextmanager 

25import time 

26 

27import astropy.units as u 

28 

29from .datum import Datum 

30from .measurement import Measurement 

31 

32 

33def _epoch_to_iso(seconds): 

34 """Convert a time in seconds since Unix epoch to an ISO 8601 timestamp. 

35 

36 Parameters 

37 ---------- 

38 seconds : `float` 

39 The number of seconds since the Unix epoch. 

40 

41 Returns 

42 ------- 

43 timestamp : `str` 

44 The input time represented as a timestamp. 

45 """ 

46 iso_format = "%Y-%m-%dT%H:%M:%SZ" 

47 return time.strftime(iso_format, time.gmtime(seconds)) 

48 

49 

50@contextmanager 

51def time_this_to_measurement(measurement: Measurement): 

52 """Time the enclosed block and record it as an lsst.verify measurement. 

53 

54 Parameters 

55 ---------- 

56 measurement : `lsst.verify.Measurement` 

57 Measurement object to fill with the timing information. Its metric must 

58 have time dimensions. Any properties other than ``metric`` and 

59 ``metric_name`` may be overwritten. 

60 """ 

61 start = time.time() 

62 try: 

63 yield 

64 finally: 

65 end = time.time() 

66 measurement.quantity = (end - start) * u.second 

67 # Same metadata as provided by TimingMetricTask 

68 measurement.notes["estimator"] = "verify.timer.time_this_to_measurement" 

69 measurement.extras["start"] = Datum(_epoch_to_iso(start)) 

70 measurement.extras["end"] = Datum(_epoch_to_iso(end))