【发布时间】:2014-08-08 03:05:22
【问题描述】:
在处理时间和持续时间时发现了一个奇怪的差异,通过 ctime 输出 time_t。我绝对在这里遗漏了一些东西。在代码和输出之后有更多关于问题的信息。我搜索了一下类似的问题,如果有请指导我。
我目前正在运行: 操作系统:Windows 7 64 位 CPU:英特尔酷睿 i5 M 520 2.40Ghz 内存:4GB IDE:Microsoft Visual Studio Express 2013
编辑:完整来源
#include <iostream>
#include <chrono>
#include <ctime>
#include <thread>
using namespace std::chrono;
int main()
{
duration<int, std::milli> wait(5500);
time_point<system_clock> timePoint_Start;
time_point<system_clock> timePoint_End;
time_t timeT_Start;
time_t timeT_End;
std::cout << "01. timePoint_Start Address, sizeof: " << &timePoint_Start << ", " << sizeof(timePoint_Start) << std::endl;
std::cout << "02. timePoint_End Address, sizeof: " << &timePoint_End << ", " << sizeof(timePoint_End) << std::endl;
std::cout << "03. timeT_Start Address, sizeof: " << &timeT_Start << ", " << sizeof(timeT_Start) << std::endl;
std::cout << "04. timeT_End Address, sizeof: " << &timeT_End << ", " << sizeof(timeT_End) << std::endl;
timePoint_Start = system_clock::now(); // < = = = = set the time the 1st time
timeT_Start = system_clock::to_time_t(timePoint_Start);
std::cout << "05. Time Start: " << system_clock::to_time_t(timePoint_Start) << " " << std::ctime(&timeT_Start);
std::this_thread::sleep_for(wait);
timePoint_End = system_clock::now(); // < = = = = set the time the 2nd time
timeT_End = system_clock::to_time_t(timePoint_End);
std::cout << "06. Time End: " << system_clock::to_time_t(timePoint_End) << " " << std::ctime(&timeT_End);
duration<double> elapsed_seconds = timePoint_End - timePoint_Start;
std::cout << "07. Time Start: " << system_clock::to_time_t(timePoint_Start) << " 0x" << &timeT_Start << " " << std::ctime(&timeT_Start)
<< "08. Time Wait: duration<int, std::milli> wait(5500);" << std::endl
<< "09. Time End: " << system_clock::to_time_t(timePoint_End) << " 0x" << &timeT_End << " " << std::ctime(&timeT_End)
<< "10. Time Elapsed: " << elapsed_seconds.count() << "s" << std::endl;
std::cout << "11. Time End: " << system_clock::to_time_t(timePoint_End) << " 0x" << &timeT_End << " " << std::ctime(&timeT_End);
这是输出中出现差异的地方编辑:完整输出
01. timePoint_Start Address, sizeof: 0046FAA4, 8
02. timePoint_End Address, sizeof: 0046FA94, 8
03. timeT_Start Address, sizeof: 0046FA84, 8
04. timeT_End Address, sizeof: 0046FA74, 8
05. Time Start: 1402880407 Sun Jun 15 20:00:07 2014
06. Time End: 1402880413 Sun Jun 15 20:00:13 2014
07. Time Start: 1402880407 0x0046FA84 Sun Jun 15 20:00:07 2014
08. Time Wait: duration<int, std::milli> wait(1500);
09. Time End: 1402880413 0x0046FA74 Sun Jun 15 20:00:07 2014
10. Time Elapsed: 5.50932s
11. Time End: 1402880413 0x0046FA74 Sun Jun 15 20:00:13 2014
据我了解,输出的第 6 行、第 9 行和第 11 行的时间戳应该匹配。输出的第 9 行似乎选择了错误的引用。这里有什么语法错误吗?
我是一个菜鸟,但这看起来真的很奇怪。如果我在错误的部分,请引导我到正确的部分。真的很想知道这里发生了什么。
【问题讨论】:
-
Magic 8 球说“在变量超出范围后从变量中读取”,但发布的代码看起来不错。你能用一个独立编译的样本来编辑你的样本,但仍然在你的机器上重现问题吗?
-
我已经运行了您发布的代码,它似乎没问题。你确定这正是你所拥有的吗?
-
@Joseph 刚刚又跑了一遍代码,结果还是一样的,我觉得乔纳森的回答是合理的。
标签: c++ c++11 output duration ctime