C++ VMWare Fusion/Boot Camp 下 VS2010 中 ctime 的 clock() 方法出现问题

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

本文关键字:clock 方法 问题 ctime Fusion VMWare Boot Camp VS2010 C++      更新时间:2023-10-16

在Mac上的特定情况下,我很难从ctime库中的clock()方法中获得任何有用的东西。具体来说,如果我试图在VMWare Fusion或Boot Camp下在Windows7中运行VS2010,它似乎总是返回相同的值。一些测试代码来测试问题:

#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;
}

在Xcode 4.3.3下,该函数在大约2μs内执行。

在Windows 7虚拟机中的Visual Studio 2010下(在VMWare Fusion 4.1.3下),相同的代码给出的执行时间为0;这台机器配备了Mac 4核中的2核和2GB RAM。

在运行Windows7的Boot Camp下,我再次获得0的执行时间。

这是一个"离金属太远"的问题吗?

可能是在虚拟机下计时器的分辨率没有那么高。编译器可以很容易地将尾部递归转换为循环;60次乘法运算往往不会花很长时间。尝试计算一些明显更昂贵的东西,比如斐波那契数(当然是递归的),你应该会看到计时器继续

从MSVC、中包含的time.h

#define CLOCKS_PER_SEC  1000

这意味着当使用Visual C++运行时库时,clock()的分辨率仅为1毫秒,因此任何一组耗时小于1毫秒的操作几乎总是被测量为零时间。

有关Windows上可以帮助您的更高分辨率计时,请查看QueryPerformanceCounter以及这个示例代码。