YARP
Yet Another Robot Platform
PlatformTime.cpp
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2006-2021 Istituto Italiano di Tecnologia (IIT)
3  * SPDX-FileCopyrightText: 2006-2010 RobotCub Consortium
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
8 
9 #include <yarp/os/Time.h>
10 #include <chrono>
11 #include <cmath>
12 #include <thread>
13 
14 //time helper functions
16  if (Time::isSystemClock()) {
17 #ifdef YARP_HAS_ACE
18  now = ACE_OS::gettimeofday();
19 #else
20  struct timezone *tz = nullptr;
21  gettimeofday(&now, tz);
22 #endif
23  } else {
24 #ifdef YARP_HAS_ACE
25  now.set(Time::now());
26 #else
27  double t = Time::now();
28  now.tv_sec = lround(t);
29  now.tv_usec = lround((t-now.tv_sec)*1e6);
30 #endif
31  }
32 }
33 
34 
36  if (Time::isSystemClock()) {
37  std::this_thread::sleep_for(std::chrono::duration<double>(toDouble(sleep_period)));
38  } else {
39  Time::delay(toDouble(sleep_period));
40  }
41 }
42 
43 
45 #ifdef YARP_HAS_ACE
46  val += add;
47 #else
48  val.tv_usec += add.tv_usec;
49  int over = val.tv_usec % 1000000;
50  if (over != val.tv_usec) {
51  val.tv_usec = over;
52  val.tv_sec++;
53  }
54  val.tv_sec += add.tv_sec;
55 #endif
56 }
57 
58 
60 #ifdef YARP_HAS_ACE
61  val -= subtract;
62 #else
63  if (val.tv_usec > subtract.tv_usec) {
64  val.tv_usec -= subtract.tv_usec;
65  val.tv_sec -= subtract.tv_sec;
66  return;
67  }
68  int over = 1000000 + val.tv_usec - subtract.tv_usec;
69  val.tv_usec = over;
70  val.tv_sec--;
71  val.tv_sec -= subtract.tv_sec;
72 #endif
73 }
74 
75 
77 #ifdef YARP_HAS_ACE
78  return double(v.sec()) + v.usec() * 1e-6;
79 #else
80  return double(v.tv_sec) + v.tv_usec * 1e-6;
81 #endif
82 }
83 
84 
85 void yarp::os::impl::fromDouble(YARP_timeval &v, double x, int unit) {
86 #ifdef YARP_HAS_ACE
87  v.msec(lround(x*1000/unit+0.5));
88 #else
89  v.tv_usec = lround(x*1000000/unit+0.5) % 1000000;
90  v.tv_sec = lround(x/unit);
91 #endif
92 }
float t
double now()
Return the current time in seconds, relative to an arbitrary starting point.
Definition: Time.cpp:121
void delay(double seconds)
Wait for a certain number of seconds.
Definition: Time.cpp:111
bool isSystemClock()
Check if YARP is providing system time.
Definition: Time.cpp:262
void addTime(YARP_timeval &val, const YARP_timeval &add)
void getTime(YARP_timeval &now)
double toDouble(const YARP_timeval &v)
struct timeval YARP_timeval
Definition: PlatformTime.h:32
void subtractTime(YARP_timeval &val, const YARP_timeval &subtract)
void sleepThread(YARP_timeval &sleep_period)
void fromDouble(YARP_timeval &v, double x, int unit=1)