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

回眸只為那壹抹淺笑 提交于 2019-12-03 12:49:22

A cross platform way is to use ftime.

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

Example 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 through it using VS2008 and saw it actually calls the windows GetSystemTimeAsFileTime function.

Anyway, ftime will give you milliseconds precision.

The solution below seems OK 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;
}

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

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

GetSystemTime() uses the structure SYSTEMTIME, which provides milli-second resolution.

More on this here.

This code piece works. This is based on the answer from Angus Comber:

#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
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!