1

I am making a piece of code that will tell me how much time did a "block of code" took to execute. My approach for this problem is that I create two instances of timer_t , give the first instance the current time before the start of execution of that "block of code" and then give the second instance the current time when it finishes executing that. Then I take the difference of both the instances to calculate the running time. The code looks like this: (Visual Studio used)

#include "stdafx.h"
#include<stdio.h>
#include<conio.h>
#include<iostream>
#include<Windows.h>
#include<stdlib.h>
#include<time.h>


using namespace std;



int _tmain(int argc, _TCHAR* argv[])
{


    srand((unsigned)time(NULL));


    for(int i=0;i<10;i++)
    {
        cout<<rand()%100<<endl;
    }



    cout<<endl;
    time_t timernow,timerthen;

    timernow=time(NULL);
    Sleep(300);
    timerthen=time(NULL);

    cout<<"Elapsed time: "<<timerthen-timernow;

    _getch();



    return 0;
}

But the problem with this is that it gives me time in only seconds (0 in this case instead of 0.3) but I want the time in milliseconds or so. Is it possible to increase the resolution/precision of time? Thank You.

Akshay Arora
  • 1,953
  • 1
  • 14
  • 30

1 Answers1

2

Use <chrono>. It has facilities for time measurement, including a high precision clock and duration_cast.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    Although correct, a little snippet showing *how* to time using `` would not be amiss; from the OP's example code, I would deduce (s)he is a beginner. – Matthieu M. Aug 07 '14 at 09:01