【问题标题】:Discrepancies between g++ output and Visual Studio Output. Float Variablesg++ 输出和 Visual Studio 输出之间的差异。浮点变量
【发布时间】:2014-10-08 00:55:06
【问题描述】:

我正在使用 c++ 中的 clock_t 函数进行测试,但遇到了一个问题。当我编译时,我在 2 个不同的编译器上进行。我的 Windows 7 计算机(2012)上的 Visual Studio,以及名为“ranger”的 Unix 系统上的 g++。当我刚刚编译我的代码以尝试以秒为单位输出运行不同排序函数所需的时间(最多千分之一秒)时,g++ 编译器似乎完全忽略了我将时间戳除以 1000 的尝试为了将它从毫秒转换为第二种格式。有什么建议吗?在这方面,g++ 和 Visual Studio 的编译器有区别吗?

一个短代码sn-p(输出和我为除法做什么):

//Select Sort

begin = clock(); //Begin time
selectionSort(array, n);
end = clock(); //End time
d_select = ((float)(end/1000.0) - (float)(begin/1000.0)); //Calculates the time in MS, and converts from MS, to a float second.

//Output data
cout << setprecision(3) << fixed; //Set precision to 3 decimal places, with a fixed output (0's are displayed regardless of rounding)
cout << n << "\t" << d_bubble << "\t" << d_insert << "\t" << d_merge << "\t" << d_quick << "\t"
    << d_select << endl;

Visual Studio 输出(正确):

n       Bubble      Insert      Merge       Quick       Select  
100000  12.530      1.320       0.000       0.030       2.900

Unix 输出(不正确):

n       Bubble      Insert      Merge       Quick       Select  
100000  51600.000   11700.000   30.000      150.000     18170.000

有什么建议吗?谢谢!

【问题讨论】:

    标签: c++ visual-studio-2012 io g++ iomanip


    【解决方案1】:

    除以CLOCKS_PER_SEC,而不是 1000。在 Unix 和一般的 POSIX 上,clock() 给出的值以微秒为单位,而不是毫秒。

    请注意,clock_t 是整数;因此,如果您想要小数秒,请在除法之前转换为浮点格式:

    d_select = float(end - begin) / CLOCKS_PER_SEC;
    

    【讨论】:

    • 这样做,它似乎只给我一个整数答案,所以任何花费不到一秒的排序函数(通常会给我类似 546 MS 的例子)现在只会给我0.000 作为“结果”,好像根本不需要时间。难道我不能打一个通用的“从时间转换为秒”的电话吗?
    • @DavidRutledge:所以转换为除法的浮点格式,例如float(end-start)/CLOCKS_PER_SEC.
    • 啊哈!似乎我对浮点数的转换没有按照我的预期工作(我只是用 CLOCKS_PER_SEC 替换了我的代码中的 1000)。但是,以您编写的方式使用它似乎可以解决问题。非常感谢!看来我今天学到了 Unix 和 Microsoft 编译器的另一个区别。
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多