Sunday, May 28, 2017

tic and toc functions in C++ (millisecond resolution)

This is a newer version of my original post about Matlab-like tic/toc functions in C++

These new versions of the TIC/TOC functions have millisecond resolution while the old ones rounded the time difference to the seconds.

Here is the the new  tic_toc.h header:

#ifndef TIC_TOC_H
#define TIC_TOC_H

#include <iostream>
#include <chrono>

typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;

static Clock::time_point t0 = Clock::now();

void tic()
t0 = Clock::now();

void toc()
    Clock::time_point t1 = Clock::now();
    milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    std::cout <<"Elapsed time is "<< ms.count() << " milliseconds\n";


// happy coding and performance testing :)