发现一个奇怪的差异,通过ctime输出time_t,同时搞乱计时和持续时间。我绝对错过了这里的一些东西。在代码和输出之后有关于该问题的更多信息。我搜索了一下类似的问题,如果有的话请指导我。
我目前正在投放: 操作系统:Windows 7 64位 CPU:Intel Core 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行似乎是错误的引用。这里有什么语法错误吗?
我是新手,但这似乎是一种奇怪的行为。如果我在错误的部分,请指导我到正确的部分。真的想知道这里发生了什么。
答案 0 :(得分:6)
我相信std::ctime()
函数来自C标准,在C标准中,它返回一个指向静态内存位置的指针。这一次只能存储一个值。由于你有一次使用std::cout << ...
3次的大量std::ctime()
调用,你运气不好;您将在所有三个位置显示一个值,而不是3个不同的值(通常 - 虽然详细信息取决于对ctime()
的调用与<<
运算符的调用交错的方式,这取决于编译器)。
最简单的方法是修改代码,使标记为7,8,9,10的行是单独的语句。
长期修复需要更多考虑。