2 * Written in 2013 by Gregor Pintar <grpintar@gmail.com>
4 * To the extent possible under law, the author(s) have dedicated
5 * all copyright and related and neighboring rights to this software
6 * to the public domain worldwide.
8 * This software is distributed without any warranty.
10 * You should have received a copy of the CC0 Public Domain Dedication.
11 * If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
16 #if defined(PERF_UNIX)
22 #elif defined(PERF_WINDOWS)
30 #if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__))
34 #if defined(PERF_WINDOWS) || defined(PERF_RDTSC)
38 typedef uint64_t perf_int
;
39 #define PERF_INT_MAX UINT64_MAX
45 typedef clock_t perf_int
;
46 #define PERF_INT_MAX (clock_t)UINT64_MAX
50 inline perf_int
perf_clock(void)
52 #if defined(PERF_WINDOWS) && defined(PERF_QPC)
56 QueryPerformanceCounter(&x
);
60 #elif defined(PERF_RDTSC)
74 return (((uint64_t)hi
) << 32) | lo
;
76 #elif defined(_POSIX_CPUTIME)
80 if(clock_gettime(CLOCK_PROCESS_CPUTIME_ID
, &x
))
81 perror("clock_gettime()");
83 return (((uint64_t)x
.tv_sec
) << 32) | x
.tv_nsec
;
97 cycles = perf_clock(); \
98 for(i = 0; i < 1000000; i++) \
103 cycles = (perf_clock() - cycles) / 1000000; \
113 cycles = PERF_INT_MAX; \
114 for(i = 0; i < 1000000; i++) \
119 t1 = perf_clock() - t0 - perf_c; \
120 if(cycles > t1) cycles = t1; \
132 #if defined(PERF_UNIX)
134 struct sched_param p
;
139 /* lock process to one core */
142 if(sched_setaffinity(0, CPU_ALLOC_SIZE(1), &set
))
143 perror("sched_setaffinity()");
146 puts("For better results disable dynamic CPU frequency scaling!");
148 /* set highest possible priority */
149 for(p
.sched_priority
= sched_get_priority_max(SCHED_FIFO
);
150 p
.sched_priority
; p
.sched_priority
--)
152 if(!sched_setscheduler(0, SCHED_FIFO
, &p
)) break;
154 printf("SCHED_FIFO with priority: %u\n", p
.sched_priority
);
156 #elif defined(PERF_WINDOWS)
158 SYSTEM_POWER_CAPABILITIES s
;
160 /* disable dynamic CPU frequency scaling */
161 if(CallNtPowerInformation(SystemPowerCapabilities
, 0, 0, &s
, sizeof(s
)) == STATUS_SUCCESS
)
163 if(s
.ProcessorMinThrottle
!= 100 || s
.ProcessorMaxThrottle
!= 100)
165 s
.ProcessorMinThrottle
= 100;
166 s
.ProcessorMaxThrottle
= 100;
167 if(CallNtPowerInformation(SystemPowerCapabilities
, &s
, sizeof(s
), 0, 0) != STATUS_SUCCESS
)
168 puts("Can't disable dynamic CPU frequency scaling!");
171 else puts("Can't disable dynamic CPU frequency scaling!");
174 if(!SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS
))
175 puts("SetPriorityClass() failed!");
177 /* lock process to one core */
178 if(!SetProcessAffinityMask(GetCurrentProcess(), 1))
179 puts("SetProcessAffinityMask() failed!");
192 #if defined(PERF_UNIX)
194 #elif defined(PERF_WINDOWS)