I am testing out using the clock_t function's in c++ and I ran across a problem. When I compile I do it on 2 different compilers. Visual studio on my Windows 7 computer (2012), and g++ on a Unix system called "ranger". When I just compiled my code in an attempt to output the time in seconds (up to a thousandth of a second) it takes to run different sort functions, it seems that the g++ compiler completely ignores my attempt to divide the time stamp by 1000 in order to convert it from milliseconds to a second format. Any advice? Is there a difference between g++ and Visual Studio's compiler in regard's to this?
A short code snippet(Output and what i do for division):
//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 output (Correct):
n Bubble Insert Merge Quick Select
100000 12.530 1.320 0.000 0.030 2.900
Unix output(Incorrect) :
n Bubble Insert Merge Quick Select
100000 51600.000 11700.000 30.000 150.000 18170.000
Any suggestions? Thanks!
Divide by CLOCKS_PER_SEC
, not 1000. On Unix, and POSIX in general, clock()
gives a value in microseconds, not milliseconds.
Note that that, and clock_t
, are integers; so if you want fractional seconds, convert to a floating-point format before dividing:
d_select = float(end - begin) / CLOCKS_PER_SEC;