Skip to content

Instantly share code, notes, and snippets.

@matutter
Last active August 29, 2015 14:12
Show Gist options
  • Select an option

  • Save matutter/dfec00fc4be88f27f0a0 to your computer and use it in GitHub Desktop.

Select an option

Save matutter/dfec00fc4be88f27f0a0 to your computer and use it in GitHub Desktop.
CPU speed, requires c++11 or c++0x
#include <chrono>
#include <iostream>
#include <unistd.h>
class Timer {
private:
static inline unsigned long long CPUCycleCounter(void) {
unsigned long long int x;
__asm__ volatile (".byte 0x0F, 0x31" : "=A" (x));
return x;
}
unsigned long long _start;
double _tdiv, _res;
std::chrono::duration<long long int, std::ratio<1ll, 1000000ll> > _period;
std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<long long int, std::ratio<1ll, 1000000ll> > > _begin, _end;
std::string _unit;
public:
Timer() {
clear();
_tdiv = 1;
}
Timer(double t, std::string u) {
clear();
_tdiv = t;
_unit = u;
}
void start() {
clear();
_begin = std::chrono::high_resolution_clock::now() ;
_start = CPUCycleCounter();
}
void stop() {
_res = ( CPUCycleCounter() - _start ) / _tdiv;
_end = std::chrono::high_resolution_clock::now() ;
_period = std::chrono::duration_cast<std::chrono::microseconds>(_end-_begin);
}
void clear() {
_start = _res = 0;
}
std::string getRes() {
return "Timer: " + std::to_string(_res) + _unit;
}
void test() {
std::cout << "CPU appears to be " << (_res/_period.count())*1000000.0f << _unit<<"/s" << std::endl;
}
};
class TimerGHz : public Timer {
public:
TimerGHz() : Timer(1000000000.0f, "Ghz") {}
};
class TimerMHz : public Timer {
public:
TimerMHz() : Timer(1000000.0f, "Mhz") {}
};
int main ()
{
std::cout << "Calculating...\n" ;
TimerGHz timer;
timer.start();
usleep(200);
timer.stop();
timer.test();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment