linux C語言 計時

在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;

}

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

 注: 根據Linux下clock計時函數學習,可以精確到10ms

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;//打印時間

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章