Issue #14104: Implement time.monotonic() on Mac OS X,
authorVictor Stinner <victor.stinner@gmail.com>
Mon, 12 Mar 2012 23:25:42 +0000 (00:25 +0100)
committerVictor Stinner <victor.stinner@gmail.com>
Mon, 12 Mar 2012 23:25:42 +0000 (00:25 +0100)
patch written by Nicholas Riley.

Misc/NEWS
Modules/timemodule.c

index 5cf2e7e55970a1308b86adb2de9b48039f8b502a..3fe824ffe56ef20f09b81b93da383822ab2f5dc3 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -24,6 +24,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #14104: Implement time.monotonic() on Mac OS X, patch written by
+  Nicholas Riley.
+
 - Issue #13394: the aifc module now uses warnings.warn() to signal warnings.
 
 - Issue #14252: Fix subprocess.Popen.terminate() to not raise an error under
index 59fe3eef03e2650b0efd4c0424622cb2da2a4ba4..6ebd3efc97820744311ddfd7f896fd42474263b5 100644 (file)
 #include <sys/time.h>
 #endif
 
+#if defined(__APPLE__)
+#include <mach/mach_time.h>
+#endif
+
 /* Forward declarations */
 static int floatsleep(double);
 static double floattime(void);
@@ -816,7 +820,8 @@ of the returned value is undefined so only the difference of consecutive\n\
 calls is valid.");
 
 #if (defined(MS_WINDOWS) && !defined(__BORLANDC__)) \
-    || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC))
+    || (defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)) \
+    || (defined(__APPLE__))
 #  define HAVE_PYTIME_MONOTONIC
 #endif
 
@@ -826,6 +831,17 @@ time_monotonic(PyObject *self, PyObject *unused)
 {
 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
     return win32_clock(0);
+#elif defined(__APPLE__)
+    uint64_t time = mach_absolute_time();
+    double secs;
+
+    static mach_timebase_info_data_t timebase;
+    if (timebase.denom == 0)
+      mach_timebase_info(&timebase);
+
+    secs = (double)time * timebase.numer / timebase.denom * 1e-9;
+
+    return PyFloat_FromDouble(secs);
 #else
     static int clk_index = 0;
     clockid_t clk_ids[] = {