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

后端 未结 6 1775
栀梦
栀梦 2021-02-14 09:39

I\'ve searched in the Web but I\'ve only found a way for do it, but in this way it returns in seconds instead of milliseconds.

My code is:

#include 

        
6条回答
  •  我在风中等你
    2021-02-14 10:32

    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 
    #include  
    
    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.

提交回复
热议问题