C语言学习:获取系统时间

头文件定义

 1 #ifndef CHAPTER10_INCLUDE_TIME_UTILS_H_
 2 #define CHAPTER10_INCLUDE_TIME_UTILS_H_
 3 
 4 #if defined(_WIN32)
 5 #include <sys/timeb.h>
 6 #elif defined(__unix__) || defined(__APPLE__)
 7 #include <sys/time.h>
 8 #endif
 9 
10 typedef long long long_time_t;
11 
12 long_time_t TimeInMillisecond(void) {
13 #if defined(_WIN32)
14   struct timeb time_buffer;
15   ftime(&time_buffer);
16   return time_buffer.time * 1000LL + time_buffer.millitm;
17 #elif defined(__unix__) || defined(__APPLE__)
18   struct timeval time_value;
19   gettimeofday(&time_value, NULL);
20   return time_value.tv_sec * 1000LL + time_value.tv_usec / 1000;
21 #elif defined(__STDC__) && __STDC_VERSION__ == 201112L
22   struct timespec timespec_value;
23   timespec_get(&timespec_value, TIME_UTC);
24   return timespec_value.tv_sec * 1000LL + timespec_value.tv_nsec / 1000000;
25 #else
26   time_t current_time = time(NULL);
27   return current_time * 1000LL;
28 #endif
29 }
30 
31 #endif //CHAPTER10_INCLUDE_TIME_UTILS_H_
View Code

源代码

 1 #include <io_utils.h>
 2 #include <time_utils.h>
 3 #include <time.h>
 4 
 5 int main() {
 6   time_t current_time;
 7   time(&current_time);
 8   PRINT_LONG(current_time);
 9 
10   current_time = time(NULL);
11   PRINT_LONG(current_time);
12 
13   PRINT_LLONG(TimeInMillisecond());
14   PRINT_LLONG(TimeInMillisecond());
15   PRINT_LLONG(TimeInMillisecond());
16   PRINT_LLONG(TimeInMillisecond());
17 
18   return 0;
19 }
View Code

 

posted @ 2023-02-12 12:56  泥古拉斯赵四  阅读(38)  评论(0编辑  收藏  举报