我使用std::chrono
工具测量了几个时间差。我对 float 和 double 类型都进行了测试。结果令人惊讶。double 类型转到第...0000000
7 位或...9999999
之后,而 float 类型继续显示有效数字。
编码:
std::chrono::steady_clock::time_point Start, End;
std::chrono::duration<float, std::ratio<1, 1>> fDuration;
std::chrono::duration<double, std::ratio<1, 1>> dbDuration;
std::cout.precision(20);
std::cout << std::fixed;
for (DWORD dwSleepTime=0; dwSleepTime<=10000; dwSleepTime+=1000)
{
Start = std::chrono::steady_clock::now();
Sleep(dwSleepTime);
End = std::chrono::steady_clock::now();
fDuration = std::chrono::duration_cast<std::chrono::duration<float>>(End - Start);
dbDuration = std::chrono::duration_cast<std::chrono::duration<double>>(End - Start);
std::cout << "Time passed (float) = " << fDuration.count() << std::endl;
std::cout << "Time passed (double) = " << dbDuration.count() << std::endl << std::endl;
}
它的输出:
Time passed (float) = 0.00000000000000000000
Time passed (double) = 0.00000000000000000000
Time passed (float) = 1.00005722045898440000
Time passed (double) = 1.00005720000000010000
Time passed (float) = 2.00011444091796870000
Time passed (double) = 2.00011440000000020000
Time passed (float) = 3.00017166137695310000
Time passed (double) = 3.00017159999999980000
Time passed (float) = 4.00022888183593750000
Time passed (double) = 4.00022880000000040000
Time passed (float) = 5.00028610229492190000
Time passed (double) = 5.00028600000000000000
Time passed (float) = 6.00034332275390620000
Time passed (double) = 6.00034319999999970000
Time passed (float) = 7.00040006637573240000
Time passed (double) = 7.00040040000000020000
Time passed (float) = 8.00045776367187500000
Time passed (double) = 8.00045760000000070000
Time passed (float) = 9.00051498413085940000
Time passed (double) = 9.00051479999999950000
Time passed (float) = 10.00057220458984400000
Time passed (double) = 10.00057200000000000000
这种现象背后的原因是什么?在这种特殊情况下,双精度类型真的给出不太精确的结果吗?
我的系统:
IDE:Visiual Studio 2012
操作系统:Windows 7 x64
CPU:Intel i5 750