Reputation: 2802
I am trying to get a timestamp at the start of my run, another one at the end of my run and print both at the end of the run. However, apparently both timestamps are the same: the timestamps of the end. This is my code:
#include <iostream>
#include <chrono>
#include <thread>
int main(){
std::time_t now = std::time(nullptr);
char * t_start, * t_end;
t_start = std::asctime(std::localtime(&now));
std::this_thread::sleep_for(std::chrono::nanoseconds(5000000000));
now = std::time(nullptr);
t_end = std::asctime(std::localtime(&now));
std::cout<<"Started at "<<t_start<<std::endl;
std::cout<<"Ended at "<<t_end<<std::endl;
return 0;
}
For which the output is
Started at Thu Jan 21 09:54:32 2021
Ended at Thu Jan 21 09:54:32 2021
even though there was a 5 seconds delay between the two timestamps. I believe the problem is related to pointers pointing to the same "time-acquiring" object so my question is how to save the start time t_start
so that I can print it later on? Printing t_start
at the beginning gives the right timestamp, however, I need both of them at the end.
Upvotes: 0
Views: 808
Reputation: 62063
Look at asctime()
:
Return value
Pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between std::asctime and std::ctime, and may be overwritten on each invocation of any of those functions.
You're printing the same string twice. To correct it, you'll need to make a new string buffer for each.
Alternatively, you can wait to format your time until you need to print it:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
std::time_t t_start = std::time(nullptr);
std::this_thread::sleep_for(std::chrono::seconds(5));
std::time_t t_end = std::time(nullptr);
std::cout << "Started at "
<< std::asctime(std::localtime(&t_start))
<< std::endl;
std::cout << "Ended at "
<< std::asctime(std::localtime(&t_end))
<< std::endl;
return 0;
}
Result:
Started at Thu Jan 21 09:12:45 2021
Ended at Thu Jan 21 09:12:50 2021
Upvotes: 2
Reputation: 37647
This is good example how bad can be hidden state (global variable).
std::asctime - cppreference.com
Return value
Pointer to a static null-terminated character string holding the textual representation of date and time. The string may be shared between
std::asctime
and std::ctime, and may be overwritten on each invocation of any of those functions.
Basically std::asctime
always returns same pointer, but updates its local static buffer.
So to fix it you can't retain pointer for later use.
Here is fixed version: https://godbolt.org/z/r491W7
Upvotes: 2