How to measure time difference in c++

I want to measure the time of a call duration but i dont know how to do it. Please help me.
thanks.
explain your problem by jxt giving a sample run what u actually want?
This is the code that I got but it has some errors and not running. Also i want to use <chrono>, which people say is advance but i have no clue as to how we will use it? Can you help me??


#include <iostream>
#include <conio.h>
#include <time.h>
#include <stdio.h>
#include <iostream.h>


double diffclock(double clock_t clock1,double clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
return diffms;
}

int main ()
{
char c[1000];
int i;
clock_t begin=clock();
cout << "Hi what is your name? ";
cin >>c;
clock_t end=clock();
cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
return 0;
}
Last edited on
The C library clock() function only has a second resolution. You'll need an OS-specific function to get a finer resolution. Even then, though, you typically need to repeat a subroutine a good number of times to get a good idea of how long it takes a subroutine to complete. For user inputs, which I think you want here, see http://www.cplusplus.com/forum/beginner/28855/3/#msg159698 for an example of doing the same thing.

Hope this helps.
Could you tell me how would you use <chrono> to get the time differnece between a phone call being made as an example?
Alas, I'm new to it also.

I suggest you get a couple of chrono::time_point <chrono::high_resolution_clock>s and use a chrono::duration object to calculate the time difference in your preferred units.

There's a tutorial here:
http://www.boost.org/doc/libs/1_47_0/doc/html/chrono/users_guide.html#chrono.users_guide.tutorial

Good luck!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <chrono>
#include <iostream>

int main()
{

    std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now() ;

    // the operation to time (for elapsed time)
    char ch ; std::cout << '?' && std::cin >> ch ;

    std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now() ;

    typedef std::chrono::duration<int,std::milli> millisecs_t ;
    millisecs_t duration( std::chrono::duration_cast<millisecs_t>(end-start) ) ;
    std::cout << duration.count() << " milliseconds.\n" ;
}




> The C library clock() function only has a second resolution.

The C library clock() function has an implementation defined CLOCKS_PER_SEC resolution. clock() measures the approximate processor time used, and not the elapsed time.
Last edited on
Oops, my bad.
Topic archived. No new replies allowed.