Search code examples
c++macosctimevmware-fusionbootcamp

C++ Trouble with ctime's clock() method in VS2010 under VMWare Fusion/Boot Camp


I'm having trouble getting anything useful from the clock() method in the ctime library in particular situations on my Mac. Specifically, if I'm trying to run VS2010 in Windows 7 under either VMWare Fusion or on Boot Camp, it always seems to return the same value. Some test code to test the issue:

#include <time.h>
#include "iostream"

using namespace std;

// Calculate the factorial of n recursively.
unsigned long long recursiveFactorial(int n) {
    // Define the base case.
    if (n == 1) {
        return n;
    }

    // To handle other cases, call self recursively.
    else {
        return (n * recursiveFactorial(n - 1));
    }
}

int main() {
    int n = 60;
    unsigned long long result;
    clock_t start, stop;

    // Mark the start time.
    start = clock();

    // Calculate the factorial of n;
    result = recursiveFactorial(n);

    // Mark the end time.
    stop = clock();

    // Output the result of the factorial and the elapsed time.
    cout << "The factorial of " << n << " is " << result << endl;
    cout << "The calculation took " << ((double) (stop - start) / CLOCKS_PER_SEC) << " seconds." << endl;

    return 0;
}

Under Xcode 4.3.3, the function executes in about 2 μs.

Under Visual Studio 2010 in a Windows 7 virtual machine (under VMWare Fusion 4.1.3), the same code gives an execution time of 0; this machine is given 2 of the Mac’s 4 cores and 2GB RAM.

Under Boot Camp running Windows 7, again I get an execution time of 0.

Is this a question of being "too far from the metal"?


Solution

  • From time.h included with MSVC,

    #define CLOCKS_PER_SEC  1000
    

    which means clock() only has a resolution of 1 millisecond when using the Visual C++ runtime libraries, so any set of operations that takes less than that will almost always be measured as having zero time elapsed.

    For higher resolution timing on Windows that can help you, check out QueryPerformanceCounter and this sample code.