Skip to content

Instantly share code, notes, and snippets.

@carl-mastrangelo
Created July 1, 2020 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carl-mastrangelo/ca22d6f94f93e58155b53f3a361d65b9 to your computer and use it in GitHub Desktop.
Save carl-mastrangelo/ca22d6f94f93e58155b53f3a361d65b9 to your computer and use it in GitHub Desktop.
#include <x86intrin.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <inttypes.h>
static __inline__ uint64_t rdtsc(void){
uint32_t hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (uint64_t)lo)|( ((uint64_t)hi)<<32 );
}
#define COUNT 1024
int main(int argc, char ** argv) {
uint64_t a1;
uint64_t a2;
uint64_t cnt;
int i;
uint64_t *counts = calloc(COUNT, 64);
for (i = 0; i < 1000000000; i ++) {
a1 = rdtsc();
a2 = rdtsc();
cnt = a2 - a1;
if (cnt >= COUNT || cnt <= 0) {
if (cnt > 100000) {
printf("%" PRIu64 "\n", cnt);
}
} else {
counts[(int)cnt]++;
}
}
for (i = 10; i < 100; i++) {
printf("%d - %ld\n", i, counts[i]);
}
return 0;
}
$ gcc out.c -Wall -Werror -ansi -pedantic -O3 -o bang
$ perf stat -- ./bang
$ # lots of output
Performance counter stats for './bang':
14,705.11 msec task-clock # 1.000 CPUs utilized
44 context-switches # 0.003 K/sec
0 cpu-migrations # 0.000 K/sec
69 page-faults # 0.005 K/sec
50,144,334,653 cycles # 3.410 GHz
16,014,174,095 instructions # 0.32 insn per cycle
2,002,637,169 branches # 136.186 M/sec
126,570 branch-misses # 0.01% of all branches
14.706359541 seconds time elapsed
14.705729000 seconds user
0.000000000 seconds sys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment