Skip to content

Instantly share code, notes, and snippets.

@jepio
Created February 1, 2022 10:35
Show Gist options
  • Select an option

  • Save jepio/f0b73345642af147e372ab138be1fb88 to your computer and use it in GitHub Desktop.

Select an option

Save jepio/f0b73345642af147e372ab138be1fb88 to your computer and use it in GitHub Desktop.
Compute cpu frequency. This works because lines 12-17 are dependent operations which can't be pipelined and so must take 10 cycles.
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
// Perform CYCLES simple in-order operations
unsigned loop(int CYCLES)
{
unsigned a = rand(), b = rand(), x = rand();
for (int i=0; i < CYCLES/10; i++)
{
x = (x + a) ^ b;
x = (x + a) ^ b;
x = (x + a) ^ b;
x = (x + a) ^ b;
x = (x + a) ^ b;
}
return x;
}
int main(int argc, char *argv[])
{
int CYCLES = 1000*1000*1000;
unsigned x = loop(CYCLES/10); // warm up the cpu
struct timeval tm, tn;
gettimeofday(&tm, NULL);
x += loop(CYCLES);
gettimeofday(&tn, NULL);
double t1 = (tn.tv_sec - tm.tv_sec) +
(tn.tv_usec - tm.tv_usec) / 1e6;
if (x)
printf("Time: %.6f s, CPU freq %.2f GHz\n", t1, (CYCLES/1e9)/t1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment