Naruto
10/14/2017 - 10:49 AM

rdtsc_x64.c

//
//
// cc rdtsc_x64.c -o rdtsc_x64
// ./rdtsc_x64

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

// Taken from stackoverflow (see http://stackoverflow.com/questions/3830883/cpu-cycle-count-based-profiling-in-c-c-linux-x86-64)
// Can give nonsensical results on multi-core AMD processors.
uint64_t rdtsc64() {
    uint32_t lo, hi;
    asm volatile (
        "cpuid \n" /* serializing */
        "rdtsc"
        : "=a"(lo), "=d"(hi) /* outputs */
        : "a"(0) /* inputs */
        : "%ebx", "%ecx");
    /* clobbers*/
    return ((uint64_t) lo) | (((uint64_t) hi) << 32);
}

uint64_t startRDTSC(void) {
    return rdtsc64();
}

uint64_t stopRDTSCP(void) {
    return rdtsc64();
}

int main() {

    uint64_t start, end;

    start = startRDTSC();    
    sleep(1);
    end = stopRDTSCP();

    printf("start: %lld\n", start);
    printf("end:   %lld\n", end);
    printf("%lld\n", end-start);
    return 0;
}