Skip to content

Instantly share code, notes, and snippets.

@nfarring
Created January 17, 2012 04:36
Show Gist options
  • Save nfarring/1624742 to your computer and use it in GitHub Desktop.
Save nfarring/1624742 to your computer and use it in GitHub Desktop.
Intel RDTSC (Read Timestamp Counter) Instruction
#include <stdio.h>
#include "rdtsc.h"
int main(int argc, char *argv[]) {
uint64_t timestamp[10000];
uint64_t diff;
int i;
for (i = 0; i < 10000; i++) {
timestamp[i] = rdtsc();
}
for (i = 1; i < 10000; i++) {
diff = timestamp[i] - timestamp[i-1];
printf("%lu\n", diff);
}
return 0;
}
main: main.c
.PHONY:
clean:
rm -f main
#ifndef __RDTSC_H__
#define __RDTSC_H__
#ifdef __cplusplus
#include <cstdint>
#else
#include <stdint.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
__inline__ uint64_t rdtsc(void) {
uint32_t lo;
uint32_t hi;
__asm__ __volatile__ ( // serialize
"xorl %%eax,%%eax \n cpuid"
::: "%rax", "%rbx", "%rcx", "%rdx");
/* We cannot use "=A", since this would use %rax on x86_64 and return only the lower 32bits of the TSC */
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}
#ifdef __cplusplus
}
#endif
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment