Belle II Software development
Time.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#include "daq/slc/system/Time.h"
9
10#include "daq/slc/base/Reader.h"
11#include "daq/slc/base/Writer.h"
12
13#include <sys/time.h>
14
15#include <cmath>
16#include <cstdlib>
17#include <sstream>
18
19using namespace Belle2;
20
21#define MEGA 1000000
22
23Time::Time()
24{
25 timeval tv;
26 gettimeofday(&tv, 0);
27 m_s = tv.tv_sec;
28 m_us = tv.tv_usec;
29}
30
31Time::Time(const double t)
32{
33 set(t);
34}
35
36Time::Time(const long s, const long us)
37 : m_s(s), m_us(us)
38{
39 adjust();
40}
41
42Time::~Time()
43{
44}
45
46void Time::adjust()
47{
48 if (MEGA <= labs(m_us)) {
49 m_s += m_us / MEGA;
50 m_us = m_us - (m_us / MEGA) * MEGA;
51 }
52 if (0 < m_s && m_us < 0) {
53 m_s--;
54 m_us += MEGA;
55 }
56 if (m_s < 0 && 0 < m_us) {
57 m_s++;
58 m_us -= MEGA;
59 }
60}
61
62void Time::clear()
63{
64 m_s = m_us = 0;
65}
66
67void Time::set()
68{
69 timeval tv;
70 gettimeofday(&tv, 0);
71 m_s = tv.tv_sec;
72 m_us = tv.tv_usec;
73}
74
75void Time::set(const double t)
76{
77 double s, us;
78 us = modf(t, &s);
79 m_s = (long)s;
80 m_us = (long)(us * 1000000);
81 adjust();
82}
83
84void Time::set(const long s, const long us)
85{
86 m_s = s;
87 m_us = us;
88 adjust();
89}
90
91double Time::get() const
92{
93 return (double)m_s + ((double)m_us) / 1000000.;
94}
95
96long Time::getSecond() const
97{
98 return m_s;
99}
100
101long Time::getMicroSecond() const
102{
103 return m_us;
104}
105
106std::string Time::toString() const
107{
108 std::stringstream ss;
109 ss << m_s << "." << m_us;
110 return ss.str();
111}
112
113void Time::readObject(Reader& r)
114{
115 m_s = r.readLong();
116 m_us = r.readLong();
117}
118
119void Time::writeObject(Writer& w) const
120{
121 w.writeLong(m_s);
122 w.writeLong(m_us);
123}
124
125bool Time::operator == (const Time& t) const
126{
127 return (m_s == t.m_s) && (m_us == t.m_us);
128}
129
130Time Time::operator + (const Time& t) const
131{
132 Time tt = *this;
133 tt.m_s += t.m_s;
134 tt.m_us += t.m_us;
135 return tt;
136}
137
138Time Time::operator - (const Time& t) const
139{
140 Time tt = *this;
141 tt.m_s -= t.m_s;
142 tt.m_us -= t.m_us;
143 return tt;
144}
145
Abstract base class for different kinds of events.