3

I am writing a program and attempting to time the number of seconds that passes when a given block of code runs. Afterwards I would like to print the total time it took to run the block of code in seconds. What I have written is:

time_t start = time(0);
// block of code
double seconds_since_start = difftime(time(0), start);
printf("seconds since start: %2.60f\n", seconds_since_start);

I have printf() printing to 60 decimal precision and all of the times still come out to 0.000000...

Is there an error in my time function? I find it hard to believe that the task I am asking to time would not account for any time in 60 decimal precision.

raphnguyen
  • 3,565
  • 18
  • 56
  • 74
  • time() returns seconds. If the time elapsed is < 1 second, you'll always see 0 printed in our output. – craig65535 Apr 01 '13 at 18:44
  • You can always use ``. – chris Apr 01 '13 at 18:48
  • @craig65535: not always! Not if you start timing just before the second changes. – TonyK Apr 01 '13 at 18:48
  • @TonyK: Oh great, so now you see "1 second" even when the actual elapsed time was 1000 times smaller. – Ben Voigt Apr 01 '13 at 18:49
  • @TonyK true. What I should have said is, you'll see clock changes, not elapsed time. So you could potentially see "0 seconds since start" for a job that took 900 ms, and you could potentially see "1 second since start" for a job that took 1 ms, depending on how close your clock was to a seconds change. – craig65535 Apr 01 '13 at 18:58

5 Answers5

7

You can use the date and time utilities available in C++11:

#include <chrono>
#include <iostream>
#include <thread>

int main()
{
    auto start = std::chrono::high_resolution_clock::now();

    std::this_thread::sleep_for(std::chrono::seconds(5));

    auto end = std::chrono::high_resolution_clock::now();

    auto difference = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();

    std::cout << "Seconds since start: " << difference;
}
Rob
  • 26,989
  • 16
  • 82
  • 98
David G
  • 94,763
  • 41
  • 167
  • 253
  • Instead of the high resolution timer, you might want the monotonic timer. – Ben Voigt Apr 01 '13 at 18:58
  • @BenVoigt: I'm sorry, what's the difference between the high resolution timer and the monotonic timer? Castiblanco's solution works, but I don't like the fact that it relies on writing your own function. Isn't it better to use a standard package that includes the functions you need to achieve what you want? – raphnguyen Apr 01 '13 at 19:07
  • @raphnguyen: The monotonic timer measures passing time. Other times are based on the system calendar. Usually the same, but if the user (or NTP client service) updates the system date or time while your program is running... – Ben Voigt Apr 01 '13 at 19:08
  • @David: Thanks for the demo. I have modified it to return microseconds and then I divide that by `1000000` in order to get fractional seconds: http://liveworkspace.org/code/YT1I$6. It seems to work well in the demo, but in my program I only get values of `0` or `0.001`. Is there a reason for this? – raphnguyen Apr 01 '13 at 19:31
  • @raphnguyen If you want it to return microseconds then simply replace `std::chrono::seconds` in the `duration_cast<>` with [`std::chrono::microseconds`](http://en.cppreference.com/w/cpp/chrono/duration). – David G Apr 01 '13 at 19:35
  • @David: Yes, that's what I did in the link I posted in the comment above. For some reason my program is only returning values of `0` and `0.001` which seems highly unlikely to me that it would only have microseconds of `0` or `1000`. – raphnguyen Apr 01 '13 at 19:38
  • @raphnguyen I'm not sure why that's happening. I get a value like `0.044405` when I run it. Maybe the compiler is optimizing away the for loop for you. – David G Apr 01 '13 at 19:41
  • @David: Strange indeed, but thanks for your help. I'll try and post another question to troubleshoot. – raphnguyen Apr 01 '13 at 19:43
  • @David: Do you think it may have something to do with me using `monotonic_clock` instead? I can't seem to get `monotonic_clock` to work in the LWS demo. – raphnguyen Apr 01 '13 at 19:49
  • @raphnguyen There's no object named `monotonic_clock`. Try `std::chrono::steady_clock` in place of `high_resolution_clock`. See what happens. – David G Apr 01 '13 at 19:50
  • @David: There is an object named `monotonic_clock` on Windows at least, but `steady_clock` seems to result in the same return values of either `0` or `0.001`. – raphnguyen Apr 01 '13 at 19:56
  • Ok David is right, `steady_clock` is exactly what I should have suggested. – Ben Voigt Apr 01 '13 at 23:22
5

The return value from time is an integral number of seconds. Casting to a double won't bring back the fractional seconds that have been lost.

You need a more precise clock function, such as gettimeofday (if you want wall-clock time) or times (if you want CPU time).

On Windows, there's timeGetTime, QueryPerformanceCounter (which Castiblanco demonstrates), or GetSystemTimeAsFileTime.

C++ finally got some standard high-resolution clock functions with C++11's <chrono> header, suggested by chris in the comments.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
2

Actually I prefer to do it with milliseconds, because there are tons of function that can return 0 if you use just seconds, for this reason It's better to use milliseconds.

#include <time.h>

double performancecounter_diff(LARGE_INTEGER *a, LARGE_INTEGER *b){
  LARGE_INTEGER freq;
  QueryPerformanceFrequency(&freq);
  return (double)(a->QuadPart - b->QuadPart) / (double)freq.QuadPart;
}


int main()
{

LARGE_INTEGER t_inicio, t_final;
double sec;

QueryPerformanceCounter(&t_inicio);    

// code here, the code that you need to knos the time.

QueryPerformanceCounter(&t_final);

sec = performancecounter_diff(&t_final, &t_inicio);

printf("%.16g millisegudos\n", sec * 1000.0);*/

}

return 0;
}
Castiblanco
  • 1,200
  • 4
  • 13
  • 32
1

you can use boost::timer

template<typename T>
double sortTime(std::vector<T>& v, typename sort_struct<T>::func_sort f){
    boost::timer t; // start timing
    f(v);
    return t.elapsed();
}
4pie0
  • 29,204
  • 9
  • 82
  • 118
0

Something like that should work:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() 
{ 
    clock_t begin, end;
    double time_spent;

    begin = clock();

    //Do stuff

    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("%Lf\n",time_spent);
} 
Johnny Mnemonic
  • 3,822
  • 5
  • 21
  • 33