CTimeSpan总是为零 [英] CTimeSpan always gets zero
问题描述
我想获得插入排序算法的运行时间。 MSDN说使用CTime可以得到经过时间。但我尝试了很多次,总是为零。我认为运行这个算法的时间是不可能的。必须有一些错误或别的东西。有人帮助我吗?我发布我的代码如下:
I am trying to get the running time of Insertion Sort Algorithm. MSDN said that using CTime could get the Elapsed Time. But I tried many times and always got zero. I thought it is impossible that the time of running this algorithm is zero. There must be some error or something else. Could anybody help me? I posted my code below:
#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
推荐答案
并不意味着时间的分辨率小于一秒。我想你真正的后是像 GetTickCount
或 GetTickCount64
。请参阅此MSDN 链接 。
CTime isn't meant to time things to a resolution less than one second. I think what you are really after is something like GetTickCount
or GetTickCount64
. See this MSDN link .
GetTickCount函数
GetTickCount function
检索自系统以来经过的毫秒数
Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
如果使用 GetTickCount64
,您可以声明 startTime
和 endTime
这样:
If using GetTickCount64
you could declare startTime
and endTime
this way:
uint64_t endTime, startTime, diffTime;
然后使用 GetTickCount64
毫秒的类似
startTime = GetTickCount64();
... do stuff ...
endTime = GetTickCount64();
diffTime = endTime - startTime;
当然也可以使用diffTime。
And of course diffTime can be used however you want.
如果你不需要时间超过一个月,你可以使用 GetTickCount
,返回的类型将是 uint32_t
而不是 uint64_t
If you don't need to time things for more than a month then you can simply use GetTickCount
and the type returned will be a uint32_t
instead of uint64_t
如果您需要超过1毫秒的分辨率您的计算机支持高分辨率定时器,则此代码可能工作:
If you need resolution beyond 1 millisecond for timing and your computer supports a high resolution timer then this code may work:
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中找到条目
Information on the high performance timer can be found in this MSDN entry
这篇关于CTimeSpan总是为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!