jeudi 21 janvier 2021

Saving timestamp in C++11

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.

Aucun commentaire:

Enregistrer un commentaire