How to get time elapsed through C in milliseconds? (Windows)

I searched on the Internet, but I found a way to do this, but that way it returns in seconds instead of milliseconds.

My code is:

#include <stdio.h> #include <assert.h> #include <time.h> int main(void) { int solucion; time_t start, stop; clock_t ticks; long count; time(&start); solucion = divisores_it(92000000, 2); time(&stop); printf("Finnished in %f seconds. \n", difftime(stop, start)); return 0; } 
+6
source share
5 answers

A cross-platform way is to use ftime.

Windows Link: http://msdn.microsoft.com/en-us/library/aa297926(v=vs.60).aspx

An example is below.

 #include <stdio.h> #include <sys\timeb.h> int main() { struct timeb start, end; int diff; int i = 0; ftime(&start); while(i++ < 999) { /* do something which takes some time */ printf("."); } ftime(&end); diff = (int) (1000.0 * (end.time - start.time) + (end.millitm - start.millitm)); printf("\nOperation took %u milliseconds\n", diff); return 0; } 

I ran the code above and traced it using VS2008 and saw that it actually calls the GetSystemTimeAsFileTime function on Windows.

In any case, ftime will give you millisecond accuracy.

+20
source

The solution below seems convenient to me. What do you think?

 #include <stdio.h> #include <time.h> long timediff(clock_t t1, clock_t t2) { long elapsed; elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000; return elapsed; } int main(void) { clock_t t1, t2; int i; float x = 2.7182; long elapsed; t1 = clock(); for (i=0; i < 1000000; i++) { x = x * 3.1415; } t2 = clock(); elapsed = timediff(t1, t2); printf("elapsed: %ld ms\n", elapsed); return 0; } 

Link: http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.15.html#clock

+9
source

GetSystemTime() uses the SYSTEMTIME structure, which provides resolution in milliseconds.

Read more about it here .

+1
source

For Windows, GetSystemTime() is what you want. For POSIX gettimeofday() .

+1
source

This piece of code works. This is based on Angus Comber's answer:

 #include <sys/timeb.h> uint64_t system_current_time_millis() { #if defined(_WIN32) || defined(_WIN64) struct _timeb timebuffer; _ftime(&timebuffer); return (uint64_t)(((timebuffer.time * 1000) + timebuffer.millitm)); #else struct timeb timebuffer; ftime(&timebuffer); return (uint64_t)(((timebuffer.time * 1000) + timebuffer.millitm)); #endif } 
0
source

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


All Articles