Debian Codegraph @

pyinstrument/low_level/pyi_floatclock.c

raw symbols SCIP
1 #include "pyi_floatclock.h"
2
3 #include <Python.h>
4 #include <time.h> // gettimeofday, clock()
5 #include <float.h> // DBL_MAX
6
7
8 /*
9 The windows implementations mostly stolen from timemodule.c
10 */
11
12 #if defined(MS_WINDOWS) && !defined(__BORLANDC__)
13 #include <windows.h>
14
15 double pyi_monotonic_coarse_resolution(void)
16 {
17 return DBL_MAX;
18 }
19
20 /* use QueryPerformanceCounter on Windows */
21
22 double pyi_floatclock(PYIFloatClockType timer)
23 {
24 if (timer == PYI_FLOATCLOCK_MONOTONIC_COARSE) {
25 warn_once("CLOCK_MONOTONIC_COARSE not available on this system.");
26 }
27 static LARGE_INTEGER ctrStart;
28 static double divisor = 0.0;
29 LARGE_INTEGER now;
30 double diff;
31
32 if (divisor == 0.0) {
33 LARGE_INTEGER freq;
34 QueryPerformanceCounter(&ctrStart);
35 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
36 /* Unlikely to happen - this works on all intel
37 machines at least! Revert to clock() */
38 return ((double)clock()) / CLOCKS_PER_SEC;
39 }
40 divisor = (double)freq.QuadPart;
41 }
42 QueryPerformanceCounter(&now);
43 diff = (double)(now.QuadPart - ctrStart.QuadPart);
44 return diff / divisor;
45 }
46
47 #else /* !MS_WINDOWS */
48
49 #include <unistd.h>
50 #include <sys/time.h> // clock_gettime
51
52 static double SEC_PER_NSEC = 1e-9;
53 static double SEC_PER_USEC = 1e-6;
54
55 double pyi_monotonic_coarse_resolution(void)
56 {
57 #ifdef CLOCK_MONOTONIC_COARSE
58 static double resolution = -1;
59 if (resolution == -1) {
60 struct timespec res;
61 int success = clock_getres(CLOCK_MONOTONIC_COARSE, &res);
62 if (success == 0) {
63 resolution = res.tv_sec + res.tv_nsec * SEC_PER_NSEC;
64 } else {
65 // clock_getres failed, so let's set the resolution to something
66 // so this timer is never used.
67 resolution = DBL_MAX;
68 }
69 }
70 return resolution;
71 #else
72 return DBL_MAX;
73 #endif
74 }
75
76 double pyi_floatclock(PYIFloatClockType timer)
77 {
78 // gets the current time in seconds, as quickly as possible.
79 #ifdef _POSIX_TIMERS
80 struct timespec t;
81 int res;
82 if (timer == PYI_FLOATCLOCK_MONOTONIC_COARSE) {
83 # ifdef CLOCK_MONOTONIC_COARSE
84 res = clock_gettime(CLOCK_MONOTONIC_COARSE, &t);
85 if (res == 0) return t.tv_sec + t.tv_nsec * SEC_PER_NSEC;
86 # else
87 warn_once("CLOCK_MONOTONIC_COARSE not available on this system.");
88 # endif
89 }
90 # ifdef CLOCK_MONOTONIC
91 res = clock_gettime(CLOCK_MONOTONIC, &t);
92 if (res == 0) return t.tv_sec + t.tv_nsec * SEC_PER_NSEC;
93 # endif
94 res = clock_gettime(CLOCK_REALTIME, &t);
95 if (res == 0) return t.tv_sec + t.tv_nsec * SEC_PER_NSEC;
96 #endif
97 struct timeval tv;
98 gettimeofday(&tv, (struct timezone *)NULL);
99 return (double)tv.tv_sec + tv.tv_usec * SEC_PER_USEC;
100 }
101
102 #endif /* MS_WINDOWS */