Measuring time in C

前端 未结 5 1687
青春惊慌失措
青春惊慌失措 2020-12-14 09:26

I\'m trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:

clock_t start = clock();
sleep(3);
clock_t e         


        
5条回答
  •  生来不讨喜
    2020-12-14 09:45

    As a side note, if you want to measure execution time in a more precise manner (milliseconds), time is not precise enough. You can use gettimeofday instead:

    #include 
    #include 
    #include 
    
    int main() {
        long start, end;
        struct timeval timecheck;
    
        gettimeofday(&timecheck, NULL);
        start = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000;
    
        usleep(200000);  // 200ms
    
        gettimeofday(&timecheck, NULL);
        end = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000;
    
        printf("%ld milliseconds elapsed\n", (end - start));
    
        return 0;
    }
    

提交回复
热议问题