Skip to content

Instantly share code, notes, and snippets.

@falkTX
Created April 21, 2016 08:41
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save falkTX/7b56638989db140d8eddc3ca2203eb5f to your computer and use it in GitHub Desktop.
Save falkTX/7b56638989db140d8eddc3ca2203eb5f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdint.h>
#include <time.h>
static inline
uint64_t getCycles(void)
{
#if defined(__ARM_ARCH_7A__)
uint32_t r;
asm volatile("mrc p15, 0, %0, c9, c13, 0\t\n" : "=r" (r)); /* Read PMCCNTR */
return ((uint64_t)r) << 6; /* 1 tick = 64 clocks */
#elif defined(__x86_64__)
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
return ((uint64_t)a) | (((uint64_t)d) << 32);
#elif defined(__i386__)
uint64_t ret;
asm volatile("rdtsc": "=A" (ret));
return ret;
#else
return 0;
#endif
}
static inline
uint32_t getMillisecondCounter(void)
{
struct timespec t;
clock_gettime (CLOCK_MONOTONIC, &t);
return (uint32_t) (t.tv_sec * 1000 + t.tv_nsec / 1000000);
}
static inline
int getClockSpeed(void)
{
const uint64_t cycles = getCycles();
const uint32_t millis = getMillisecondCounter();
int lastResult = 0;
for (;;)
{
int n = 1000000;
while (--n > 0) {}
const uint32_t millisElapsed = getMillisecondCounter() - millis;
const uint64_t cyclesNow = getCycles();
if (millisElapsed > 80)
{
const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
return newResult;
lastResult = newResult;
}
}
}
int main()
{
printf("Clock speed: %i MHz | %.3f GHz\n", getClockSpeed(), ((double)getClockSpeed())/1000.0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment