Unix/Linux計算程式消耗的時間(毫秒)

來源:互聯網
上載者:User

使用time(NULL)得到的是從1970年1月1日到目前的秒,這種精度很多時候是不夠用的。為了得到毫秒級的精度,需要使用gettimeofday:

直接上代碼:

#include <sys/time.h>#include <stdlib.h>#include <stdio.h>#include <math.h>// Return 1 if the difference is negative, otherwise 0.  int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){    long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);    result->tv_sec = diff / 1000000;    result->tv_usec = diff % 1000000;    return (diff<0);}void timeval_print(struct timeval *tv){    char buffer[30];    time_t curtime;    printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);    curtime = tv->tv_sec;    strftime(buffer, 30, "%m-%d-%Y  %T", localtime(&curtime;));    printf(" = %s.%06ld\n", buffer, tv->tv_usec);}int main(){    struct timeval tvBegin, tvEnd, tvDiff;    // begin    gettimeofday(&tvBegin;, NULL);    timeval_print(&tvBegin;);    // lengthy operation    int i,j;    for(i=0;i<999999L;++i) {        j=sqrt(i);    }    //end    gettimeofday(&tvEnd;, NULL);    timeval_print(&tvEnd;);    // diff    timeval_subtract(&tvDiff;, &tvEnd;, &tvBegin;);    printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);    return 0;}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.