[Patch] [libc++] Don't use <sys/time.h>/gettimeofday() when possible
Ed Schouten
ed at 80386.nl
Tue Oct 7 04:43:43 PDT 2014
Hi there,
I am currently doing some experiments to see how easy/hard it is to
get libc++ to work in an environment that only implements a 'sane'
subset of POSIX.
Looking at time functions that are provided by POSIX, it seems that
<sys/time.h> is slowly being deprecated in favour of <time.h>.
clock_gettime() and friends are part of the base definitions, whereas
gettimeofday() is only part of the optional X/Open System Interfaces.
libc++'s src/chrono.cpp already uses clock_gettime() on all platforms
for CLOCK_MONOTONIC, except on OS X, where clock_gettime() is not
available. I would really love to see us do the same for the real-time
clock, where we just use CLOCK_REALTIME, instead of using
gettimeofday().
Attached is a patch that adds exactly this. Would anyone mind if I
were to push this patch into the tree one of these days?
Link: http://80386.nl/pub/20141007-libcxx-gettimeofday.txt
Thanks,
--
Ed Schouten <ed at 80386.nl>
-------------- next part --------------
Index: include/chrono
===================================================================
--- include/chrono (revision 219076)
+++ include/chrono (working copy)
@@ -915,7 +915,7 @@
class _LIBCPP_TYPE_VIS system_clock
{
public:
- typedef microseconds duration;
+ typedef nanoseconds duration;
typedef duration::rep rep;
typedef duration::period period;
typedef chrono::time_point<system_clock> time_point;
Index: src/chrono.cpp
===================================================================
--- src/chrono.cpp (revision 219076)
+++ src/chrono.cpp (working copy)
@@ -8,13 +8,13 @@
//===----------------------------------------------------------------------===//
#include "chrono"
-#include <sys/time.h> //for gettimeofday and timeval
#ifdef __APPLE__
+#include <sys/time.h> // for gettimeofday and timeval
#include <mach/mach_time.h> // mach_absolute_time, mach_timebase_info_data_t
#else /* !__APPLE__ */
#include <cerrno> // errno
#include <system_error> // __throw_system_error
-#include <time.h> // clock_gettime, CLOCK_MONOTONIC
+#include <time.h> // clock_gettime, CLOCK_MONOTONIC and CLOCK_REALTIME
#endif // __APPLE__
_LIBCPP_BEGIN_NAMESPACE_STD
@@ -29,9 +29,16 @@
system_clock::time_point
system_clock::now() _NOEXCEPT
{
+#ifdef __APPLE__
timeval tv;
gettimeofday(&tv, 0);
- return time_point(seconds(tv.tv_sec) + microseconds(tv.tv_usec));
+ return time_point(seconds(tv.tv_sec) + nanoseconds(tv.tv_usec * 1000));
+#else // __APPLE__
+ struct timespec tp;
+ if (0 != clock_gettime(CLOCK_REALTIME, &tp))
+ __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
+ return time_point(seconds(tp.tv_sec) + nanoseconds(tp.tv_nsec));
+#endif // __APPLE__
}
time_t
More information about the cfe-commits
mailing list