一、時間用途
根據實踐需要,時間有不同的使用方式。
場景1:等待xx秒執行某個動作,這個等待在計算機系統的程序中是如何實現的?
場景2:獲取當前年月日等基本時間信息
場景3:計算代碼執行時間
二、獲取時間方式1:函數"clock_gettime"
此函數是基於Linux C語言的時間函數,可以用於計算精度和納秒。
要點:與Linux系統強相關。
頭文件和函數聲明如下:
#include<time.h>
int clock_gettime(clockid_t clk_id, struct timespec *tp);
說明:
- clk_id : 檢索和設置的clk_id指定的時鍾時間。
- CLOCK_REALTIME:系統實時時間,隨系統實時時間改變而改變,即從UTC1970-1-1 0:0:0開始計時,中間時刻如果系統時間被用戶改成其他,則對應的時間相應改變
- CLOCK_MONOTONIC:從系統啟動這一刻起開始計時,不受系統時間被用戶改變的影響
- CLOCK_PROCESS_CPUTIME_ID:本進程到當前代碼系統CPU花費的時間
- CLOCK_THREAD_CPUTIME_ID:本線程到當前代碼系統CPU花費的時間
- 時間參數結構體:
struct timespec
{
time_t tv_sec; /* 秒*/
long tv_nsec; /* 納秒*/
};
三、獲取時間方式2:函數“gettimeofday”
gettimeofday是計算機函數,使用C語言編寫程序需要獲得當前精確時間(1970年1月1日到現在的時間),或者為執行計時,可以使用gettimeofday()函數。
特點:與系統無關,便於移植。
頭文件和函數聲明如下:
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
其參數tv是保存獲取時間結果的結構體,參數tz用於保存時區結果:
struct timezone{
int tz_minuteswest; /*格林威治時間往西方的時差*/
int tz_dsttime; /*DST 時間的修正方式*/
}
timezone 參數若不使用則傳入NULL即可。
而結構體timeval的定義為:
struct timeval{
long int tv_sec; // 秒數
long int tv_usec; // 微秒數
}
它獲得的時間精確到微秒(1e6s)量級。
在一段代碼前后分別使用gettimeofday可以計算代碼執行時間:
struct timeval tv_begin, tv_end;
gettimeofday(&tv_begin, NULL);
foo();
//process ...
gettimeofday(&tv_end, NULL);
函數執行成功后返回0,失敗后返回-1,錯誤代碼存於errno中。
四、示例代碼
#include<stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
typedef unsigned int uint32_t;
#define csp_sleep_ms(time_ms) usleep(time_ms * 1000);
uint32_t csp_get_ms() {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
return (ts.tv_sec*1000+ts.tv_nsec/1000000);
} else {
return 0;
}
}
uint32_t csp_get_ms_another(){
struct timeval tv;
struct timespec ts;
if (gettimeofday(&tv, NULL))
return 0;
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
return ts.tv_sec*1000+ts.tv_nsec/1000000;
}
int main()
{
uint32_t start = csp_get_ms();
csp_sleep_ms(1000);
uint32_t time = csp_get_ms()-start;
printf(" clock_gettime with %u ms\r\n", time);
uint32_t start1 = csp_get_ms_another();
csp_sleep_ms(1000);
uint32_t time1 = csp_get_ms_another()-start1;
printf(" gettimeofday with %u ms\r\n", time1);
return 0;
}
五、執行結果
gcc learntime.c
./a.out
clock_gettime with 1002 ms
gettimeofday with 1003 ms