Question

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"?

Was it helpful?

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.

OTHER TIPS

It could be that the resolution of the timer is not as high under the virtual machine. The compiler can easily convert the tail recursion into a loop; 60 multiplications don't tend to take a terribly long time. Try computing something significantly more costly, like Fibonacci numbers (recursively, of course) and you should see the timer go on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top