linux 獲取系統時間(兩種辦法,兩種精度)
阿新 • • 發佈:2019-02-03
1.、寫時間到檔案裡
void get_time()
{
time_t now;
struct tm *timenow;
FILE *fp;
char time_buffer[100] = {0};
time(&now);
timenow = localtime(&now);
fp = fopen("./time_1.txt", "a+");
if (NULL == fp)
printf("open time.txt failed\n");
sprintf(time_buffer, "%s", asctime(timenow));
fputs(time_buffer, fp);
fclose(fp);
}
2、獲取時間差,精確到微秒
timeval 是系統內部的結構體,標頭檔案
#include<sys/time.h> 最好是這個標頭檔案,<time.h> 有時候不好使
#include<unistd.h>
struct timeval
{
long tv_sec;//秒
long tv_usec;//微秒
};
int timeval_subtract(struct timeval start, struct timeval end)
{
return (1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec);
}
void get_time()
{
time_t now;
struct tm *timenow;
FILE *fp;
char time_buffer[100] = {0};
time(&now);
timenow = localtime(&now);
fp = fopen("./time_1.txt", "a+");
if (NULL == fp)
printf("open time.txt failed\n");
sprintf(time_buffer, "%s", asctime(timenow));
fputs(time_buffer, fp);
fclose(fp);
}
2、獲取時間差,精確到微秒
timeval 是系統內部的結構體,標頭檔案
#include<sys/time.h> 最好是這個標頭檔案,<time.h> 有時候不好使
#include<unistd.h>
struct timeval
{
long tv_sec;//秒
long tv_usec;//微秒
};
int timeval_subtract(struct timeval start, struct timeval end)
{
return (1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec);
}