This might sound like a basic question but I've searched a lot. I am trying to time-profile a function call in C++ & need to log the time in seconds up to 3 decimal places. For example 2.304 seconds or .791 seconds. I am trying to use std::chrono to do it like this:
auto start_time = std::chrono::system_clock::now();
DoSomeOperation();
std::chrono::duration<double> elapsed_time = std::chrono::system_clock::now() - start_time;
double execution_time = elapsed_time.count();
std::cout << "execution_time = " << execution_time << std::endl;
Following is the output I am getting:
execution_time = 1.9e-05
execution_time = 2.1e-05
execution_time = 1.8e-05
execution_time = 1.7e-05
I am sure that DoSomeOperation only takes a few milliseconds to complete & I need the number in seconds. I need the number in double to use it in a different calculation.
How can I convert this weird 1.9e-05 into a sensible number in double which yields in seconds like .304 or .067 ?
Trying the code from here, I've the same problem.
To change the output format, try std::fixed and std::setprecision
double execution_time = 0.01234;
std::cout << "execution_time = "
<< std::fixed << std::setprecision(3)
<< execution_time << std::endl;
If you have several places where you need to output the execution time, it can be converted to a string and then re-used:
double execution_time = 0.01234;
std::stringstream stream;
stream << std::fixed << std::setprecision(3) << execution_time;
std::string execution_time_as_string = stream.str();
std::cout << "execution_time = " << execution_time_as_string << std::endl;
Use
cout.setf(ios::fixed,ios::floatfield);
cout.precision(3);
cout << MyDouble;
Related
I'm trying to write a simple single header benchmarker and I understand that std::clock will give me the time that a process (thread) is in actual use.
So, given the following simplified program:
nt main() {
using namespace std::literals::chrono_literals;
auto start_cpu = std::clock();
auto start_wall = std::chrono::high_resolution_clock::now();
// clobber();
std::this_thread::sleep_for(1s);
// clobber();
auto finish_cpu = std::clock();
auto finish_wall = std::chrono::high_resolution_clock::now();
std::cerr << "cpu: "
<< start_cpu << " " << finish_cpu << " "
<< (finish_cpu - start_cpu) / (double)CLOCKS_PER_SEC << " s" << std::endl;
std::cerr << "wall: "
// << FormatTime(start_wall) << " " << FormatTime(finish_wall) << " "
<< (finish_wall - start_wall) / 1.0s << " s" << std::endl;
return 0;
}
Demo
We get the following output:
cpu: 4820 4839 1.9e-05 s
wall: 1.00007 s
I just want to clarify that the cpu time is the time that it executes the code that is not actually the sleep_for code as that is actually done by the kernel which std::clock doesn't track. So to confirm, I changed what I was timing:
int main() {
using namespace std::literals::chrono_literals;
int value = 0;
auto start_cpu = std::clock();
auto start_wall = std::chrono::high_resolution_clock::now();
// clobber();
for (int i = 0; i < 1000000; ++i) {
srand(value);
value = rand();
}
// clobber();
std::cout << "value = " << value << std::endl;
auto finish_cpu = std::clock();
auto finish_wall = std::chrono::high_resolution_clock::now();
std::cerr << "cpu: "
<< start_cpu << " " << finish_cpu << " "
<< (finish_cpu - start_cpu) / (double)CLOCKS_PER_SEC << " s" << std::endl;
std::cerr << "wall: "
// << FormatTime(start_wall) << " " << FormatTime(finish_wall) << " "
<< (finish_wall - start_wall) / 1.0s << " s" << std::endl;
return 0;
}
Demo
This gave me an output of:
cpu: 4949 1398224 1.39328 s
wall: 2.39141 s
value = 354531795
So far, so good. I then tried this on my windows box running MSYS2's g++ compiler. The output for the last program gave me:
value = 0
cpu: 15 15 0 s
wall: 0.0080039 s
std::clock() is always outputting 15? Is the compiler implementation of std::clock() broken?
Seems that I assumed that CLOCKS_PER_SEC would be the same. However, on the MSYS2 compiler, it was 1000x less then on godbolt.org.
So I'm writing a program to count the execution time of a function using clock and I used iomanip to change the output to decimal with 9 zeros.
This is the code that I am using:
#include <time.h>
#include <iomanip>
using namespace std;
void linearFunction(int input)
{
for(int i = 0; i < input; i++)
{
}
}
void execution_time(int input)
{
clock_t start_time, end_time;
start_time = clock();
linearFunction(input);
end_time = clock();
double time_taken = double(end_time - start_time) / double(CLOCKS_PER_SEC);
cout << "Time taken by function for input = " << input << " is : " << fixed
<< time_taken << setprecision(9);
cout << " sec " << endl;
}
int main()
{
execution_time(10000);
execution_time(100000);
execution_time(1000000);
execution_time(10000000);
execution_time(100000000);
execution_time(1000000000);
return 0;
}
And the output shows:
Time taken by function for input = 10000 is : 0.000000 sec
Time taken by function for input = 100000 is : 0.001000000 sec
Time taken by function for input = 1000000 is : 0.002000000 sec
Time taken by function for input = 10000000 is : 0.038000000 sec
Time taken by function for input = 100000000 is : 0.316000000 sec
Time taken by function for input = 1000000000 is : 3.288000000 sec
As you can see, the first time I call the function, it doesn't follow the setprecision(9) that I wrote. Why is this and how can I solve this? Thanks you in advance.
Look at the following line properly:
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken << setprecision(9);
See? You are setting the precision after printing out time_taken. So for the first time, you don't see the result of setprecision(). But for the second time and onwards, as setprecision() has already been executed, you get the desired decimal places.
So to fix this issue, move setprecision() before time_taken as such:
cout << "Time taken by function for input = " << input << " is : " << fixed << setprecision(9) << time_taken;
..or you can also do something like this:
cout.precision(9);
cout << "Time taken by function for input = " << input << " is : " << fixed << time_taken;
Also, consider not using the following line in your code:
using namespace std;
..as it's considered as a bad practice. Instead use std:: every time like this:
std::cout.precision(9);
std::cout << "Time taken by function for input = " << input << " is : " << std::fixed << time_taken;
For more information on this, look up to why is "using namespace std" considered as a bad practice.
I have implemented a c++ method that calculates the maximum ulp error between an approximation and a reference function on a given interval. The approximation as well as the reference are calculated as single-precision floating point values. The method starts with the low bound of the interval and iterates over each existing single-precision value within the range.
Since there are a lot of existing values depending on the range that is chosen, I would like to estimate the total runtime of this method, and print it to the user.
I tried to execute the comparison several times to calculate the runtime of one iteration. My approach was to multiply the duration of one iteration with the total number of floats existing in the range. But obviously the execution time for one iteration is not constant but depends on the number of iterations, therefore my estimated duration is not accurate at all... Maybe one could adapt the total runtime calculation in the main loop?
My question is: Is there any other way to estimate the total runtime for this particular case?
Here is my code:
void FloatEvaluateMaxUlp(float(*testFunction)(float), float(*referenceFunction)(float), float lowBound, float highBound)
{
/*initialization*/
float x = lowBound, output, output_ref;
int ulp = 0;
long long duration = 0, numberOfFloats=0;
/*calculate number of floats between lowBound and highBound*/
numberOfFloats = *(int*)&highBound - *(int*)&lowBound;
/*measure execution time of 10 iterations*/
int iterationsToEstimateTime = 1000;
auto t1 = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterationsToEstimateTime; i++)
{
printProgressInteger(i+1, iterationsToEstimateTime);
output = testFunction(x);
output_ref = referenceFunction(x);
int ulp_local = FloatCompareULP(output, output_ref);
if (abs(ulp_local) > abs(ulp))
ulp = ulp_local;
x= std::nextafter(x, highBound + 0.001f);
}
auto t2 = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
duration /= iterationsToEstimateTime;
x = lowBound;
/*output of estimated time*/
std::cout <<std::endl<<std::endl<< " Number of floats: " << numberOfFloats << " Time per iteration: " << duration << " Estimated total time: " << numberOfFloats * duration << std::endl;
std::cout << " Starting test in range [" << lowBound << "," << highBound << "]." << std::endl;
long long count = 0;
/*record start time*/
t1 = std::chrono::high_resolution_clock::now();
for (count; x < highBound; count++)
{
printProgressInteger(count, numberOfFloats);
output = testFunction(x);
output_ref = referenceFunction(x);
int ulp_local = FloatCompareULP(output, output_ref);
if (abs(ulp_local) > abs(ulp))
ulp = ulp_local;
x = std::nextafter(x, highBound + 0.001f);
}
/*record stop time and compute duration*/
t2 = std::chrono::high_resolution_clock::now();
duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
/*result output*/
std::cout <<std::endl<< std::endl << std::endl << std::endl << "*********************************************************" << std::endl;
std::cout << " RESULT " << std::endl;
std::cout << "*********************************************************" << std::endl;
std::cout << " Iterations: " << count << " Total execution time: " << duration << std::endl;
std::cout << " Max ulp: " << ulp <<std::endl;
std::cout << "*********************************************************" << std::endl;
}
I'm trying to convert a UNIX Timestamp which is in long to a Date Time string that needs to be stored in MySQL, in this format 2016-02-01 03:15:10
This is what i have so far. Its not working on the time extraction part. I couldn't find any constructor for boost::posix_time::time_duration that can take directly a boost::posix_time::ptime object. So i tried to include a workaround. But it doesn't work in the hours() part.
static inline std::string getDateTime(long timestamp) {
std::stringstream date_str;
boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);
/* workaround to somehow get a time_duration object constructed */
boost::posix_time::ptime pt_temp = boost::posix_time::from_time_t(0);
boost::gregorian::date d = pt_1.date();
boost::posix_time::time_duration td = pt_1 - pt_temp;
/* construct the Date Time string */
date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
<< td.hours() << ":" << td.minutes() << ":" << td.seconds();
return date_str.str();
}
With an Timestamp input such as 1455892259 i'm getting this 2016-02-19 404414:30:59 as a DateTime String from the function. How to actually get the correct Date Time string which in this case would be 2016-02-19 14:30:59. Using Boost for this is compulsory.
UPDATE
This is the final working function rewritten using the answer provided by Jarra McIntyre below.
static inline std::string getDateTime(long timestamp) {
std::stringstream date_str;
boost::posix_time::ptime pt_1 = boost::posix_time::from_time_t(timestamp);
boost::gregorian::date d = pt_1.date();
auto td = pt_1.time_of_day();
/* construct the Date Time string */
date_str << d.year() << "-" << std::setw(2) << std::setfill('0') << d.month().as_number() << "-" << std::setw(2) << std::setfill('0') << d.day() << " "
<< td.hours() << ":" << td.minutes() << ":" << td.seconds();
return date_str.str();
}
Use
auto td = pt_1.time_of_day();
There is no need for a workaround to get the time of day. The number of hours being displayed in your question is probably the number of hours between 1970-01-01 00:00 and 2016-02-19 14:00. For your method of getting the time_duration to work you would have to construct a ptime on the same day not at unix time 0.
I'm using the following short program to test std::clock():
#include <ctime>
#include <iostream>
int main()
{
std::clock_t Begin = std::clock();
int Dummy;
std::cin >> Dummy;
std::clock_t End = std::clock();
std::cout << "CLOCKS_PER_SEC: " << CLOCKS_PER_SEC << "\n";
std::cout << "Begin: " << Begin << "\n";
std::cout << "End: " << End << "\n";
std::cout << "Difference: " << (End - Begin) << std::endl;
}
However, after waiting several seconds to input the "dummy" value, I get the following output:
CLOCKS_PER_SEC: 1000000
Begin: 13504
End: 13604
Difference: 100
This obviously doesn't make much sense. No matter how long I wait, the difference is always somewhere around 100.
What am I missing? Is there some header I forgot to include?
I'm using Xcode with GCC 4.2.
clock() counts CPU time, so it's not adding any time if it's sitting around waiting for input.