首页 > 解决方案 > 在 C++11 中保存时间戳

问题描述

我试图在运行开始时获取时间戳,在运行结束时获取另一个时间戳,并在运行结束时打印两者。然而,显然两个时间戳是相同的:结束的时间戳。这是我的代码:

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

输出为

Started at Thu Jan 21 09:54:32 2021
Ended at Thu Jan 21 09:54:32 2021

即使两个时间戳之间有 5 秒的延迟。我相信这个问题与指向同一个“时间获取”对象的指针有关,所以我的问题是如何保存开始时间t_start以便我以后可以打印它?在开头打印t_start会给出正确的时间戳,但是最后我需要它们。

标签: c++c++11

解决方案


asctime()

返回值

指向以空字符结尾的静态字符串的指针,该字符串保存日期和时间的文本表示。该字符串可以在 std::asctime 和 std::ctime 之间共享,并且可以在任何这些函数的每次调用时被覆盖。

您要打印两次相同的字符串。要更正它,您需要为每个创建一个新的字符串缓冲区。

或者,您可以等待格式化您的时间,直到您需要打印它:

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

结果:

Started at Thu Jan 21 09:12:45 2021

Ended at Thu Jan 21 09:12:50 2021

推荐阅读