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 @   泥古拉斯赵四  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示