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

后端 未结 6 1790
栀梦
栀梦 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:39

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

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

提交回复
热议问题