Created
August 5, 2013 05:41
-
-
Save othercat/6153742 to your computer and use it in GitHub Desktop.
New method to get work in Nanoseconds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef NEW_METHOD | |
//old method | |
#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time | |
clock_serv_t cclock; | |
mach_timespec_t mts; | |
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock); | |
clock_get_time(cclock, &mts); | |
mach_port_deallocate(mach_task_self(), cclock); | |
ts->tv_sec = mts.tv_sec; | |
ts->tv_nsec = mts.tv_nsec; | |
#else | |
clock_gettime(CLOCK_REALTIME, ts); | |
#endif | |
#else | |
//new method | |
uint64_t end; | |
uint64_t elapsed; | |
uint64_t elapsedNano; | |
static mach_timebase_info_data_t sTimebaseInfo; | |
uint64_t count_start = rdtsc(); | |
uint64_t count_end; | |
// Start the clock. | |
start = mach_absolute_time(); | |
// Call getpid. This will produce inaccurate results because | |
// we're only making a single system call. For more accurate | |
// results you should call getpid multiple times and average | |
// the results. | |
getWork(); | |
// Stop the clock. | |
end = mach_absolute_time(); | |
// Calculate the duration. | |
elapsed = end - start; | |
// Convert to nanoseconds. | |
// If this is the first time we've run, get the timebase. | |
// We can use denom == 0 to indicate that sTimebaseInfo is | |
// uninitialised because it makes no sense to have a zero | |
// denominator is a fraction. | |
if ( sTimebaseInfo.denom == 0 ) { | |
(void) mach_timebase_info(&sTimebaseInfo); | |
} | |
// Do the maths. We hope that the multiplication doesn't | |
// overflow; the price you pay for working in fixed point. | |
elapsedNano = elapsed * sTimebaseInfo.numer / sTimebaseInfo.denom; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment