CTimeSpan总是得到零
问题描述:
我想获得插入排序算法的运行时间。 MSDN表示使用CTime可以获得经过的时间。但我尝试了很多次,总是得到零。我认为运行此算法的时间不可能是零。必须有一些错误或其他的东西。有人能帮助我吗?我张贴我的代码如下:CTimeSpan总是得到零
#include <cstdlib>
#include <iostream>
#include <atltime.h>
using namespace std;
//member function
void insertion_sort(int arr[], int length);
int *create_array(int arrSize);
int main() {
//Create random array
int arraySize=100;
int *randomArray=new int[arraySize];
int s;
for (s=0;s<arraySize;s++){
randomArray[s]=(rand()%99)+1;
}
CTime startTime = CTime::GetCurrentTime();
int iter;
for (iter=0;iter<1000;iter++){
insertion_sort(randomArray,arraySize);
}
CTime endTime = CTime::GetCurrentTime();
CTimeSpan elapsedTime = endTime - startTime;
double nTMSeconds = elapsedTime.GetTotalSeconds()*1000;
cout<<nTMSeconds;
return 0;
}//end of main
答
CTime并不意味着时间的东西分辨率小于一秒。我认为你真的以后就像GetTickCount
或GetTickCount64
。请参阅此MSDN link。
GetTickCount函数
检索,因为这个系统被启动,高达49.7天即所经过的毫秒数。
如果使用GetTickCount64
你可以声明startTime
和endTime
这样:
uint64_t endTime, startTime, diffTime;
然后使用GetTickCount64
来检索的东西毫秒的时间像
startTime = GetTickCount64();
... do stuff ...
endTime = GetTickCount64();
diffTime = endTime - startTime;
当然diffTime的可然而,你想要的。
如果您不需要时间事情超过一个月,那么你可以简单地使用GetTickCount
和返回的类型将是代替uint32_t
uint64_t
如果需要超出1毫秒的分辨率,时序和你计算机支持高分辨率计时器那么这个代码可能工作:
LARGE_INTEGER freq;
double time_sec = 0.0;
if (QueryPerformanceFrequency(&freq))
{
LARGE_INTEGER start;
LARGE_INTEGER stop;
QueryPerformanceCounter(&start);
// Do Stuff to time Here
QueryPerformanceCounter(&stop);
time_sec = (uint64_t)(stop.QuadPart - start.QuadPart)/(double)freq.QuadPart;
}
else {
cout << "Your computer doesn't have a high resolution timer to use";
}
在高性能计时器的信息可以在这个MSDN entry
'CTime'ħ中找到作为一秒的决议。显然,你的整个测试不到一秒钟。 – 2014-09-21 00:36:40