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