c語言計算程式已耗用時間的方法

來源:互聯網
上載者:User

1. 有時候我們要計算程式執行的時間.比如我們要對演算法進行時間分析,這個時候可以使用下面這個函數.

精確到us。
 
#include <sys/time.h> int gettimeofday(struct timeval *tv,struct timezone *tz); strut timeval { long tv_sec; /* 秒數 */ long tv_usec; /* 微秒數 */ }; gettimeofday將時間儲存在結構tv之中.tz一般我們使用NULL來代替. #include <sys/time.h< #include <stdio.h< #include <math.h< void function() { unsigned int i,j; double y; for(i=0;i<1000;i++) for(j=0;j<1000;j++) y=sin((double)i); } main() { struct timeval tpstart,tpend; float timeuse; gettimeofday(&tpstart,NULL); function(); gettimeofday(&tpend,NULL); timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ tpend.tv_usec-tpstart.tv_usec; timeuse/=1000000; printf("Used Time:%f\n",timeuse); exit(0);       }

這個程式輸出函數的執行時間,我們可以使用這個來進行系統效能的測試,或者是函數演算法的效率分析.在我機器上的一個輸出結果是: Used Time:0.556070

2.第二種是我自己經常用的,就是:

在執行程式前,加time,如:輸入time./abc ,精確到ms。

3. clock函數(精確到1/CLOCKS_PER_SEC秒,毫秒級)

#include   <iostream> 
  #include   <ctime> 
  using   namespace   std; 
  int   max(int   x,int   y) 
  { 
        return   (x>y)?x:y; 
  } 
  int   main() 
  { 
          const   double   begin=clock(); 
  for(int   i=10000;i>0;i--) 
  for(int   j=10000;j>0;j--) 
  max(i,j); 
          const   double   end=

clock(); 

  cout   <<begin<<"     "<<end; 
  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.