IBR-DTNSuite  0.12
TimeMeasurement.cpp
Go to the documentation of this file.
1 /*
2  * TimeMeasurement.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "ibrcommon/config.h"
25 
26 #include <stdio.h>
27 #include <iostream>
28 #include <iomanip>
29 
30 namespace ibrcommon
31 {
33  {
34  start(); stop();
35  }
36 
38  {
39  }
40 
42  {
43  // set start time
45  }
46 
48  {
49  // set stop time
51  }
52 
54  {
55  struct timespec diff;
56  getTime(diff);
57 
58  // merge seconds and nanoseconds
59  double delay_ms = ((double)diff.tv_sec * 1000.0) + ((double)diff.tv_nsec / 1000000.0);
60 
61  return delay_ms;
62  }
63 
65  {
66  struct timespec diff;
67  getTime(diff);
68 
69  // merge seconds and nanoseconds
70  double delay_us = ((double)diff.tv_sec * 1000000.0) + ((double)diff.tv_nsec / 1000.0);
71 
72  return delay_us;
73  }
74 
76  {
77  return _end.tv_sec - _start.tv_sec;
78  }
79 
80  std::ostream& TimeMeasurement::format(std::ostream &stream, const double value)
81  {
82 #ifdef __UCLIBC__
83  char buf[32];
84  snprintf(buf, 32, "%4.2f", value);
85  stream << std::string(buf);
86 #else
87  stream << std::setiosflags(std::ios::fixed) << std::setprecision(2) << value;
88 #endif
89  return stream;
90  }
91 
92  std::ostream &operator<<(std::ostream &stream, const TimeMeasurement &measurement)
93  {
94  struct timespec diff;
95  measurement.getTime(diff);
96 
97  // convert nanoseconds to milliseconds
98  double delay_ms = (double)diff.tv_nsec / 1000000.0;
99 
100  if (diff.tv_sec < 1)
101  {
102  TimeMeasurement::format(stream, delay_ms); stream << " ms";
103  return stream;
104  }
105 
106  // convert time interval to seconds
107  double seconds = (double)diff.tv_sec + (delay_ms / 1000.0);
108 
109  if (diff.tv_sec >= 3600)
110  {
111  TimeMeasurement::format(stream, seconds / 3600.0); stream << " h";
112  }
113  else if (diff.tv_sec >= 60)
114  {
115  TimeMeasurement::format(stream, seconds / 60.0); stream << " m";
116  }
117  else
118  {
119  TimeMeasurement::format(stream, seconds); stream << " s";
120  }
121 
122  return stream;
123  }
124 
125  void TimeMeasurement::getTime(struct timespec &diff) const
126  {
127  MonotonicClock::diff(_start, _end, diff);
128  }
129 }