c++ - 在 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
会给出正确的时间戳,但是最后我需要它们。
解决方案
返回值
指向以空字符结尾的静态字符串的指针,该字符串保存日期和时间的文本表示。该字符串可以在 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
推荐阅读
- python-3.x - 只使用一个循环来提高速度?
- halide - Halide GPU调度程序比CPU慢
- gem5 - 如何在 gem5 设置检查点以在一段时间内运行?
- javascript - 需要在测试文件中导出默认模块
- swift - 如何在 Swift 中为 UIButton 添加渐变?
- google-bigquery - 如何检查结构的所有字段是否为 NULL?
- python - 如何在我的 Raspbian Python 程序中存储变量值?
- ibm-mq - Websphere JMS 队列发送重复消息
- mysql - Mysql更新,选择替换长字符串中的指定字符
- django - Django视图没有正确重定向