简介
最近开始学习《奔跑吧Linux入门版》的实验,想要检测一下程序排序算的时间。因此想写一篇文章详细学习一下linux的时间格式函数。
linux时间结构体
根据这一片文章
提到了三种时间的结构体
time_t
#define __TIME_T_TYPE __SYSCALL_SLONG_TYPE
__STD_TYPE __TIME_T_TYPE __time_t; /* Seconds since the Epoch. */
/* Returned by `time'. */
typedef __time_t time_t;
属于一个系统的长整型数据。不过精度只有秒
struct tm
struct tm
{
int tm_sec; /* Seconds. [0-60] (1 leap second) */
int tm_min; /* Minutes. [0-59] */
int tm_hour; /* Hours. [0-23] */
int tm_mday; /* Day. [1-31] */
int tm_mon; /* Month. [0-11] */
int tm_year; /* Year - 1900. */
int tm_wday; /* Day of week. [0-6] */
int tm_yday; /* Days in year.[0-365] */
int tm_isdst; /* DST. [-1/0/1]*/
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
};
其中tm_year表示从1900年到目前计时时间间隔多少年
struct timeval
__STD_TYPE __TIME_T_TYPE __time_t; /* Seconds since the Epoch. */
__STD_TYPE __SUSECONDS_T_TYPE __suseconds_t; /* Signed count of microseconds. */
/* A time value that is accurate to the nearest
microsecond but also has a range of years. */
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
time_t使用
不过,这个精度只有秒。
#include <stdio.h> // printf
#include <time.h> // time()
#include <unistd.h> // sleep()
int main() {
time_t seconds_1;
time_t seconds_2;
seconds_1 = time(NULL);
fun(); // do something
seconds_2 = time(NULL);
printf("%lds\n", seconds_2 - seconds_1);
}
执行结果5s
struct timeval
这个可以达到us级别
#include <stdio.h> // printf
#include <sys/time.h> // struct timeval
#include <unistd.h> // sleep()
timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
{
if ( x->tv_sec>y->tv_sec )
return -1;
if ( (x->tv_sec==y->tv_sec) && (x->tv_usec>y->tv_usec) )
return -1;
result->tv_sec = ( y->tv_sec-x->tv_sec );
result->tv_usec = ( y->tv_usec-x->tv_usec );
if (result->tv_usec<0)
{
result->tv_sec--;
result->tv_usec+=1000000;
}
return 0;
}
int main() {
struct timeval start_time, over_time, consume_time;
gettimeofday(&start_time, NULL);//get the current time
// start_time = over_time;
fun(); // do something
gettimeofday(&over_time, NULL);//get the current time
timeval_subtract(&consume_time, &start_time, &over_time);
/*计算时间差104
* 计算两个时间的间隔,得到时间差
* @param struct timeval* resule 返回计算出来的时间
* @param struct timeval* x 需要计算的前一个时间
* @param struct timeval* y 需要计算的后一个时间
* return -1 failure ,0 success
**/
printf("over %lds, %ldus\n",consume_time.tv_sec,consume_time.tv_usec);
return 0;
}
clock_t
这一个类型根据 CLOCKS_PER_SEC 确定精度, us级别
#define CLOCKS_PER_SEC ((__clock_t) 1000000)
一个clock_t计数,表示 1/CLOCKS_PER_SEC 秒。
那么 1clock_t 对应 1us。
#include <stdio.h> // printf
#include <time.h> // clock_t
#include <unistd.h> // sleep()
int main() {
clock_t start_time, over_time, consume_time;
start_time = clock();
fun(); // do something
over_time = clock();
consume_time = over_time - start_time ;
printf("consume_time %ldus\n",consume_time);
return 0;
}