我正在使用clock_t函数在c++中进行测试,遇到了一个问题。当我编译时,我会在两个不同的编译器上进行编译。Visual在我的Windows 7计算机上(2012年),g++在一个称为“游侠”的Unix系统上。当我刚刚编译我的代码,试图以秒为单位(高达千分之一秒)输出运行不同排序函数所需的时间时,g++编译器似乎完全忽略了我将时间戳除以1000以便将时间戳从毫秒转换为第二格式的尝试。有什么建议吗?在这方面,g++和Visual的编译器之间有什么区别吗?
一个简短的代码片段(输出以及我为除法所做的):
//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输出(正确):
n Bubble Insert Merge Quick Select
100000 12.530 1.320 0.000 0.030 2.900Unix输出(不正确):
n Bubble Insert Merge Quick Select
100000 51600.000 11700.000 30.000 150.000 18170.000有什么建议吗?谢谢!
发布于 2014-10-08 00:57:26
除以CLOCKS_PER_SEC,而不是1000。在Unix和POSIX上,clock()给出的值通常为微秒,而不是毫秒。
请注意,它和clock_t是整数;因此,如果您想要小数秒,那么在除法前转换成浮点格式:
d_select = float(end - begin) / CLOCKS_PER_SEC;https://stackoverflow.com/questions/26247597
复制相似问题