我正在使用c ++中的clock_t函数进行测试,我遇到了一个问题。当我编译时,我在2个不同的编译器上进行。我的Windows 7计算机上的Visual Studio(2012),以及称为" ranger"的Unix系统上的g ++。当我编译我的代码以尝试输出运行不同排序函数所需的时间(最多千分之一秒)时,似乎g ++编译器完全忽略了我将时间戳除以1000的尝试为了将其从毫秒转换为第二种格式。有什么建议? g ++和Visual Studio的编译器之间有区别吗?
一个简短的代码片段(输出和我为分裂做的事):
//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
有什么建议吗?谢谢!
答案 0 :(得分:1)
除以CLOCKS_PER_SEC
,而不是1000.在Unix和POSIX上,clock()
给出一个以微秒为单位的值,而不是毫秒。
请注意,clock_t
是整数;因此,如果您需要小数秒,请在分割前转换为浮点格式:
d_select = float(end - begin) / CLOCKS_PER_SEC;