c語言計時

來源:互聯網
上載者:User

在Linux中用C語言計時可以用很多方法。

  1. 如果是想使用秒層級的技術,可用使用C語言庫<time.h>內建的clock()進行計時。如:

  #include <iostream>

  #include <time.h>

  using namespace std;

  int main()

  {

  clock_t start = clock();

  //do some process here

  clock_t end = (clock() - start)/CLOCKS_PER_SEC;

  cout<<"time comsumption is "<<end<<endl;

  }

  以上方法只能用於秒層級的計時。

  2.如果想使用毫秒層級的計時可以使用2種方法。一種是使用linux的系統庫<sys/time.h>,一種是使用CUDA的cutil的庫。

  A. 如果使用linux的系統庫,則可以使用如下方法:

  #include <sys/time.h>

  int main()

  {

  timeval starttime,endtime;

  gettimeofday(&starttime,0);

  //do some process here

  gettimeofday(&endtime,0);

  double timeuse = 1000000*(endtime.tv_sec - starttime.tv_sec) + endtime.tv_usec - startime.tv_usec;

  timeuse /=1000;//除以1000則進行毫秒計時,如果除以1000000則進行秒層級計時,如果除以1則進行微妙層級計時

  }

  timeval的結構如下:

  strut timeval

  {

  long tv_sec; /* 秒數 */

  long tv_usec; /* 微秒數 */

  };

  上述方法可以進行微妙層級的計時,當然也可以進行毫秒和秒的計時。

  B. 如果可以使用CUDA的話,則可以使用CUDA的sdk裡面的cutil庫裡面的函數。

  #include <cutil.h>

  int main()

  {

  unsigned int timer = 0;

  cutCreatTimer(&timer);//建立計時器

  cutStartTimer(&timer);//開始計時

  // do some process here

  cutStopTimer(&timer);//停止計時

  cout<<"time is "<<cutGetTimerValue(&timer)<<endl;//列印時間

  }

 

本篇文章來源於 Linux公社網站(www.linuxidc.com)  原文連結:http://www.linuxidc.com/Linux/2011-05/35580.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.