Skip to content

Instantly share code, notes, and snippets.

@jepio
Last active August 29, 2015 14:04
Show Gist options
  • Save jepio/bddf546fb76fe17e56f3 to your computer and use it in GitHub Desktop.
Save jepio/bddf546fb76fe17e56f3 to your computer and use it in GitHub Desktop.
C/C++ structs for wall-clock timing code execution.
#ifndef __CPU_TIMER_H__
#define __CPU_TIMER_H__
#include <time.h>
struct CpuTimer {
struct timespec start;
struct timespec stop;
};
typedef struct CpuTimer CpuTimer;
void start(CpuTimer *timer) { clock_gettime(CLOCK_REALTIME, &timer->start); }
void stop(CpuTimer *timer) { clock_gettime(CLOCK_REALTIME, &timer->stop); }
float elapsed(CpuTimer *timer)
{
struct timespec *start = &timer->start;
struct timespec *stop = &timer->stop;
float elapsed = (stop->tv_sec - start->tv_sec) +
1e-9 * (stop->tv_nsec - start->tv_nsec);
return elapsed;
}
#endif
#ifndef __CPU_TIMER_H__
#define __CPU_TIMER_H__
#include <ctime>
class CpuTimer {
public:
void start() { clock_gettime(CLOCK_REALTIME, &start_); }
void stop() { clock_gettime(CLOCK_REALTIME, &stop_); }
float elapsed()
{
float elapsed = (stop_.tv_sec - start_.tv_sec) +
1e-9 * (stop_.tv_nsec - start_.tv_nsec);
return elapsed;
}
private:
timespec start_;
timespec stop_;
};
#endif
// Portable C++11 timer.
#pragma once
#include <chrono>
using namespace std::chrono;
class CpuTimer {
public:
void start() { t1 = high_resolution_clock::now(); }
void stop() { t2 = high_resolution_clock::now(); }
double elapsed()
{
return duration_cast<duration<double>>(t2 - t1).count();
}
private:
high_resolution_clock::time_point t1, t2;
};
@jepio
Copy link
Author

jepio commented Jul 18, 2014

Create an instance of the struct/class, invoke start before a section to be timed, stop after, and then print the elapsed time.
C++:

#include "cputimer.hpp"
// or
#include "cputimer2.hpp"

CpuTimer timer;
timer.start();
...
timer.stop();
std::cout << "Wall time: " << timer.elapsed() << "\n";

C:

#include "cputimer.h"

CpuTimer timer;
start(&timer);
...
stop(&timer);
printf("Wall time: %f \n", elapsed(&timer));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment