CTimeSpan always gets zero

I am trying to get the runtime of an insertion sorting algorithm. MSDN has stated that using CTime can get Elapsed Time. But I tried many times and always got zero. I thought it was impossible to run this algorithm equal to zero. There must be some kind of mistake or something else. Can anyone help me out? 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 
+1
source share
1 answer

CTime is not designed to work around a problem in less than one second. I think that you are actually after something like GetTickCount or GetTickCount64 . See this MSDN link.

Gettickcount function

Gets the number of milliseconds that have passed since the system started up to 49.7 days.

If you use GetTickCount64 , you can declare startTime and endTime as follows:

 uint64_t endTime, startTime, diffTime; 

Then use GetTickCount64 to get the time in milliseconds with something like

 startTime = GetTickCount64(); ... do stuff ... endTime = GetTickCount64(); diffTime = endTime - startTime; 

And of course, diffTime can be used as you want.

If you no longer need time for more than a month, you can just use GetTickCount , and the return type will be uint32_t instead of uint64_t

If you need a resolution of more than 1 millisecond for synchronization, 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"; } 

High performance timer information can be found in this MSDN entry.

0
source

Source: https://habr.com/ru/post/976239/


All Articles