Permalink
Browse files

Portability fixes for FreeBSD and Mac OS X.

FreeBSD requires include of <netinet/in.h>
Mac gettimeofday() has problems; use a non-standard monotonic native
clock instead.
  • Loading branch information...
1 parent 5b5edbe commit 1a01b7be0ccce4b2c49cae4cc9d591c0987a5014 John David Duncan committed with Nov 19, 2010
Showing with 50 additions and 12 deletions.
  1. +1 −0 configure.ac
  2. +1 −0 libmemc.c
  3. +1 −0 main.c
  4. +47 −12 timer.c
View
1 configure.ac
@@ -29,6 +29,7 @@ AC_SEARCH_LIBS(sqrt, m)
AC_SEARCH_LIBS(pthread_create, pthread)
AC_SEARCH_LIBS(clock_gettime, rt)
+AC_CHECK_HEADERS_ONCE(mach/mach_time.h)
AC_CHECK_HEADERS_ONCE(memcached/protocol_binary.h)
AC_CHECK_FUNCS_ONCE(gethrtime clock_gettime gettimeofday)
View
1 libmemc.c
@@ -34,6 +34,7 @@
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
+#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <errno.h>
View
1 main.c
@@ -30,6 +30,7 @@
#include <sys/stat.h>
#include <sys/socket.h>
#include <netdb.h>
+#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <signal.h>
View
59 timer.c
@@ -17,34 +17,69 @@
*
* CDDL HEADER END
*/
+
+
+/*
+ * Provide gethrtime() for systems that don't have it natively.
+ */
+
#include "config.h"
+#ifndef HAVE_GETHRTIME
+
#include <sys/time.h>
#include <time.h>
+#include <stdio.h>
+
+/* Mac OS X implementation using mach_time.h */
+#if defined(HAVE_MACH_MACH_TIME_H)
+#include <mach/mach_time.h>
-#ifndef HAVE_GETHRTIME
hrtime_t gethrtime() {
- hrtime_t ret;
+ static mach_timebase_info_data_t info = {0,0};
-#ifdef HAVE_CLOCK_GETTIME
- struct timespec ts;
+ /* Initialize once */
+ if (info.denom == 0) {
+ mach_timebase_info(&info);
+ }
- if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) {
- return (-1ULL);
- }
+ return mach_absolute_time() * info.numer / info.denom;
+}
+
+/* Implementation using clock_gettime() with CLOCK_MONOTONIC */
+#elif defined(HAVE_CLOCK_GETTIME)
+
+hrtime_t gethrtime() {
+ hrtime_t ret;
+ struct timespec ts;
+
+ if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) {
+ perror("clock_gettime");
+ return (-1ULL);
+ }
+
+ ret = ts.tv_sec * 1000000000;
+ ret += ts.tv_nsec;
+
+ return ret;
+}
+
+#else
+/* Unreliable fallback implementation using gettimeofday() */
+hrtime_t gethrtime() {
+ hrtime_t ret;
- ret = (hrtime_t)ts.tv_sec * 1000000000;
- ret += ts.tv_nsec;
-#elif HAVE_GETTIMEOFDAY
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1) {
+ perror("gettimeofday");
return (-1ULL);
}
ret = (hrtime_t)tv.tv_sec * 1000000000;
ret += tv.tv_usec * 1000;
-#endif
return ret;
}
-#endif
+#endif /* #if defined(HAVE_MACH_MACH_TIME_H) */
+
+#endif /* #ifndef HAVE_GETHRTIME */

0 comments on commit 1a01b7b

Please sign in to comment.