1、linux c編程中可以使用gettimeofday()函數獲取系統的當前時間;
2、gettimeofday()函數的原型如下:
#include<sys/time.h>
int gettimeofday(struct timeval*tv,struct timezone *tz )
函數聲明所在的頭文件爲:<sys/time.h>
3、可以使用此函數做時間記錄,簡單應用如下:
/*包含頭文件*/
#include <sys/time.h>
/*變量聲明*/
#define MILLION 1000000L
struct timeval tpstart;
struct timeval tpend;
/*原函數聲明*/
static void RecordStartTime(void);
static void RecordEndTime(void);
/*函數定義實現*/
static void RecordStartTime(void)
{
if (gettimeofday(&tpstart, NULL))
{
DebugPrint(DE_ERROR,"Failed to get start time\n");
return;
}
}
static void RecordEndTime(void)
{
if (gettimeofday(&tpend, NULL))
{
DebugPrint(DE_ERROR,"Failed to get end time\n");
return ;
}
//tpend.tv_sec進行強制類型轉換爲了防止數據溢出問題
long long timedif = MILLION*((long long)tpend.tv_sec - (long long)tpstart.tv_sec) +(long long)tpend.tv_usec - (long long)tpstart.tv_usec;
printf("IAP INFO: The function_to_time took %lld microseconds\n", timedif);
}
如果想檢測一個任務執行所需要的時間,可以如下操作:
RecordStartRTime();
task()
RecordEndTime();
執行上述操作後便可以直接獲取task()任務執行所需時間。