在我的Mac上的特定情况下,我很难从ctime库中的clock()方法中获得任何有用的东西。具体地说,如果我试图在Windows7的VMWare融合或Boot Camp下运行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;
}在Xcode4.3.3下,该函数的执行时间约为2μ。
在Visual Studio2010的Windows7虚拟机中(在MacFusion4.1.3下),相同的代码给出的执行时间为0;这台机器获得了VMWare 4个核心中的2个和2 2GB的内存。
在运行Windows7的Boot Camp下,我再次得到执行时间为0。
这是一个“离金属太远”的问题吗?
发布于 2012-07-17 08:49:39
从MSVC包含的time.h开始,
#define CLOCKS_PER_SEC 1000想要在Windows上获得更高分辨率的计时功能,请查看QueryPerformanceCounter和this sample code。
发布于 2012-07-17 08:48:07
这可能是因为在虚拟机下定时器的分辨率不是很高。编译器可以很容易地将尾递归转换为循环;60次乘法不会花费太长时间。试着计算一些明显更昂贵的东西,比如斐波那契数(当然是递归的),你应该会看到计时器在计时。
https://stackoverflow.com/questions/11514562
复制相似问题