Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

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;
}

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();
}

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);
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top