C++ VMWare Fusion/Boot Camp 下 VS2010 中 ctime 的 clock() 方法出现问题
C++ Trouble with ctime's clock() method in VS2010 under VMWare Fusion/Boot Camp
在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以及这个示例代码。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 除了使用 clock() 函数之外,有没有更好的方法来以给定的频率生成/发布数据
- C++ VMWare Fusion/Boot Camp 下 VS2010 中 ctime 的 clock() 方法出现问题