几种取时间的方法(附代码)

1.上古版

最原始的取时间的方法大概就是time+localtime了,见代码:


  
  
  1. #include <stdio.h >
  2. #include < time.h >
  3. / / gcc -o time_ 1 time_ 1.c
  4. int main()
  5. {
  6. time_t tm_now;
  7. time( &tm_now); / / 或者写成 tm_now = time( NULL);
  8. / / 1.直接打印: 1970- 1- 1,00: 00: 00到现在的秒数
  9. printf( "now time is %ld second\n", tm_now);
  10. / / 2.转换成本地时间,精确到秒
  11. struct tm *p_local_tm ;
  12. p_local_tm = localtime( &tm_now) ;
  13. printf( "now datetime: %04d-%02d-%02d %02d:%02d:%02d\n",
  14. p_local_tm- >tm_year + 1900,
  15. p_local_tm- >tm_mon + 1,
  16. p_local_tm- >tm_mday,
  17. p_local_tm- >tm_hour,
  18. p_local_tm- >tm_min,
  19. p_local_tm- >tm_sec);
  20. return 0;
  21. }

其中time函数返回的是1970年到现在的秒数,精确到秒。

localtime函数是根据这个秒数和本机的时区,解析出年月日时分秒等信息。

这里特别提醒一点,localtime函数不是多线程安全的,localtime_r才是。

还要特别提醒一点,不要在信号响应函数中使用localtime或localtime_r,程序会卡死!

程序运行结果如下:

2.傻瓜版

另一个比较好用的函数是gettimeofday。

相比其他函数,gettimeofday可以精确到微秒,还可以指定时区,性能也还可以,可以满足绝大多数场景,因此叫傻瓜版。

示例代码如下:


  
  
  1. #include <stdio.h >
  2. #include <sys / time.h >
  3. #include < time.h >
  4. / / gcc -o time_ 2 time_ 2.c
  5. int main()
  6. {
  7. struct timeval tm_now;
  8. / / 1.获取当前时间戳(tv_sec, tv_usec)
  9. gettimeofday( &tm_now, NULL); / / 第二个参数是时区
  10. / / 2.转换成本地时间,精确到秒
  11. struct tm *p_local_tm;
  12. p_local_tm = localtime( &tm_now.tv_sec) ;
  13. printf( "now datetime: %04d-%02d-%02d %02d:%02d:%02d.%06ld\n",
  14. p_local_tm- >tm_year + 1900,
  15. p_local_tm- >tm_mon + 1,
  16. p_local_tm- >tm_mday,
  17. p_local_tm- >tm_hour,
  18. p_local_tm- >tm_min,
  19. p_local_tm- >tm_sec,
  20. tm_now.tv_usec); / / 有微秒时间戳了
  21. return 0;
  22. }

运行结果如下:

3.进阶版

如果微秒级别的精度还不满足要求,可以尝试下clock_gettime,代码如下:


  
  
  1. #include <stdio.h >
  2. #include <unistd.h >
  3. #include < time.h >
  4. / / gcc -o time_ 3 time_ 3.c
  5. void print_timestamp(int use_monotonic)
  6. {
  7. struct timespec tm_now;
  8. / / 1.获取当前时间戳(tv_sec, tv_usec)
  9. if( use_monotonic)
  10. clock_gettime(CLOCK_MONOTONIC, &tm_now); / / 单调时间,屏蔽手动修改时间
  11. else
  12. clock_gettime(CLOCK_REALTIME, &tm_now); / / 机器时间
  13. / / 2.转换成本地时间,精确到秒
  14. struct tm *p_local_tm;
  15. p_local_tm = localtime( &tm_now.tv_sec) ;
  16. printf( "now datetime: %04d-%02d-%02d %02d:%02d:%02d.%09ld\n",
  17. p_local_tm- >tm_year + 1900,
  18. p_local_tm- >tm_mon + 1,
  19. p_local_tm- >tm_mday,
  20. p_local_tm- >tm_hour,
  21. p_local_tm- >tm_min,
  22. p_local_tm- >tm_sec,
  23. tm_now.tv_nsec); / / 有纳秒时间戳了
  24. }
  25. int main(int argc, char **argv)
  26. {
  27. int use_monotonic = 0;
  28. int optval = 0;
  29. while ((optval = getopt(argc, argv, "Mm")) ! = EOF)
  30. {
  31. switch (optval)
  32. {
  33. case 'M':
  34. case 'm':
  35. use_monotonic = 1;
  36. break;
  37. default:
  38. break;
  39. }
  40. }
  41. while( 1)
  42. {
  43. print_timestamp( use_monotonic);
  44. sleep( 1);
  45. }
  46. return 0;
  47. }

运行结果如下:

  

clock_gettime的第一个参数可以指定一个clock_id参数:

常见的有两个:

1) CLOCK_REALTIME

即普通的时间,跟其他时间函数取出来的时间并无区别,运行效果如上。

2) CLOCK_MONOTONIC

即单调时间,跟系统的启动时间有关,不受手动修改系统时间的影响。

  

如上图,表示系统已经启动了6 05:47:53(东8区零点是1970-01-01 08:00:00)。

表面上看,这个函数精度不错,功能完备,但却存在一个突出缺点–。对于性能敏感的函数,频繁调用会影响性能,这一点我们后面仔细说。

4.专家版

专家版本的计时函数有两个突出优点:

  • 性能高:绕过内核直接读寄存器,开销很小
  • 精度高:时间测量的最小单位是1/CPU频率秒,可达0.3纳秒(假设CPU频率为3GHz)

下面是示例程序:


  
  
  1. #include <stdio.h >
  2. #include <unistd.h >
  3. #include <stdlib.h > / / for atof
  4. #include <stdint.h > / / for uint 64_t
  5. / / gcc -o time_ 4 time_ 4.c
  6. / /获取CPU频率
  7. uint 64_t get_cpu_freq()
  8. {
  9. FILE *fp =popen( "lscpu | grep CPU | grep MHz | awk {'print $3'}", "r");
  10. if(fp = = nullptr)
  11. return 0;
  12. char cpu_mhz_str[ 200] = { 0 };
  13. fgets(cpu_mhz_str, 80,fp);
  14. fclose(fp);
  15. return atof(cpu_mhz_str) * 1000 * 1000;
  16. }
  17. / /读取时间戳寄存器
  18. uint 64_t get_tsc() / / TSC = = Time Stamp Counter寄存器
  19. {
  20. #ifdef __i 386__
  21. uint 64_t x;
  22. __asm__ volatile( "rdtsc" : "=A"(x));
  23. return x;
  24. #elif defined(__amd 64__) || defined(__x 86_ 64__)
  25. uint 64_t a, d;
  26. __asm__ volatile( "rdtsc" : "=a"(a), "=d"(d));
  27. return (d < < 32) | a;
  28. # else / / ARM架构CPU
  29. uint 32_t cc = 0;
  30. __asm__ volatile ( "mrc p15, 0, %0, c9, c13, 0": "=r" (cc));
  31. return (uint 64_t)cc;
  32. #endif
  33. }
  34. int main(int argc, char **argv)
  35. {
  36. uint 64_t cpu_freq = get_cpu_freq();
  37. printf( "cpu_freq is %lu\n", cpu_freq);
  38. uint 64_t last_tsc = get_tsc();
  39. while( 1)
  40. {
  41. sleep( 1);
  42. uint 64_t cur_tsc = get_tsc();
  43. printf( "TICK(s) : %lu\n", cur_tsc - last_tsc);
  44. printf( "Second(s) : %.02lf\n", 1.0 * (cur_tsc - last_tsc) / cpu_freq);
  45. last_tsc = cur_tsc;
  46. }
  47. return 0;
  48. }

TSC的全称是Time Stamp Counter,它是一个保存着CPU运转时钟周期数的寄存器,在X86等平台下均有提供(ARM平台下是CCR-Cycle Counter Register)。

通过专门的rdtsc汇编指令,可绕过操作系统内核直接从寄存器中读取数值,因此速度极快。

通过上述的get_tsc函数可以从这个寄存器中读出一个64位的数值,连续两次读取的值的差值,即是连续两次调用之间CPU运行的周期数。用这个周期数除以CPU运行的频率(通过上面的get_cpu_freq函数获得),即可得到具体的秒数。

上述代码运行效果如下:

可以看到,我测试用的机器的CPU频率是2.9Ghz的,我每sleep一秒输出一下两次CPU计数器的差值,发现跟频率也能对的上。

事实上,上面的所有取时间的函数,都是基于底层的类似rdtsc指令封装的,我们直接使用最底层的命令,固然快且精确,但是也不可避免的要直面一些坑。

比如我们可能碰见多CPU问题、多线程问题、进程上下文切换问题,计算机主动调节CPU频率问题等。为了顺利地使用这个指令,我们就要对程序和操作系统做一系列的限制,比如rdtsc的结果不在CPU间共享、进程运行时绑定CPU以避免被切换到另外的CPU上去、禁止计算机主动调频功能等。

5.关于性能

我们写了一个测试程序,跑10亿次,取平均时间,分别测试几个函数的性能:


  
  
  1. #include <stdio.h >
  2. #include <unistd.h >
  3. #include <stdlib.h >
  4. #include <stdint.h >
  5. #include < time.h >
  6. #include <sys / time.h >
  7. / / gcc -o time_ 5 time_ 5.c
  8. uint 64_t get_ by_ time()
  9. {
  10. time_t tm_now;
  11. time( &tm_now);
  12. return tm_now;
  13. }
  14. uint 64_t get_ by_gettimeofday()
  15. {
  16. struct timeval tm_now;
  17. gettimeofday( &tm_now, NULL);
  18. return tm_now.tv_sec;
  19. }
  20. uint 64_t get_ by_clock_gettime()
  21. {
  22. struct timespec tm_now;
  23. clock_gettime(CLOCK_REALTIME, &tm_now);
  24. return tm_now.tv_sec;
  25. }
  26. uint 64_t get_cpu_freq()
  27. {
  28. FILE *fp =popen( "lscpu | grep CPU | grep MHz | awk {'print $3'}", "r");
  29. if(fp = = NULL)
  30. return 0;
  31. char cpu_mhz_str[ 200] = { 0 };
  32. fgets(cpu_mhz_str, 80,fp);
  33. fclose(fp);
  34. return atof(cpu_mhz_str) * 1000 * 1000;
  35. }
  36. uint 64_t get_ by_tsc()
  37. {
  38. uint 64_t a, d;
  39. __asm__ volatile( "rdtsc" : "=a"(a), "=d"(d));
  40. return (d < < 32) | a;
  41. }
  42. void print_diff(uint 64_t loop_ times, uint 64_t beg_tsc, uint 64_t end_tsc)
  43. {
  44. double tt_ns = ( end_tsc - beg_tsc) * 1.0 * 1000 * 1000 * 1000 / get_cpu_freq();
  45. printf( "Number Loop : %lu\n", loop_ times);
  46. printf( "Total Time : %.02lf ns\n", tt_ns);
  47. printf( "Avg Time : %.02lf ns\n", tt_ns / loop_ times);
  48. }
  49. #define LOOP_ TIMES 1000000000
  50. int main(int argc, char **argv)
  51. {
  52. uint 64_t beg_tsc, end_tsc;
  53. long loop;
  54. printf( "-------------time()-------------\n");
  55. loop = LOOP_ TIMES;
  56. beg_tsc = get_ by_tsc();
  57. while(loop--)
  58. get_ by_ time();
  59. end_tsc = get_ by_tsc();
  60. print_diff(LOOP_ TIMES, beg_tsc, end_tsc);
  61. printf( "-------------gettimeofday()-------------\n");
  62. loop = LOOP_ TIMES;
  63. beg_tsc = get_ by_tsc();
  64. while(loop--)
  65. get_ by_gettimeofday();
  66. end_tsc = get_ by_tsc();
  67. print_diff(LOOP_ TIMES, beg_tsc, end_tsc);
  68. printf( "-------------clock_gettime()-------------\n");
  69. loop = LOOP_ TIMES;
  70. beg_tsc = get_ by_tsc();
  71. while(loop--)
  72. get_ by_clock_gettime();
  73. end_tsc = get_ by_tsc();
  74. print_diff(LOOP_ TIMES, beg_tsc, end_tsc);
  75. printf( "-------------rdtsc-------------\n");
  76. loop = LOOP_ TIMES;
  77. beg_tsc = get_ by_tsc();
  78. while(loop--)
  79. get_ by_tsc();
  80. end_tsc = get_ by_tsc();
  81. print_diff(LOOP_ TIMES, beg_tsc, end_tsc);
  82. return 0;
  83. }

测试结果如下:

  

可以看到:

  • time函数最快,但是精度太低
  • gettimeofday和clock_gettime虽然精度高,但是都比较慢
  • rdtsc精度和速度都十分优秀

另外需要注意一点的是,上述测试结果跟机器配置有很大关系,我测试所用的机器是一台ubuntu虚拟机,CPU只有2.9GHz。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/279717.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【C++】开源:libev事件循环库配置使用

&#x1f60f;★,:.☆(&#xffe3;▽&#xffe3;)/$:.★ &#x1f60f; 这篇文章主要介绍libev事件循环库配置使用。 无专精则不能成&#xff0c;无涉猎则不能通。——梁启超 欢迎来到我的博客&#xff0c;一起学习&#xff0c;共同进步。 喜欢的朋友可以关注一下&#xff0c…

代码回滚(git reset)后push失败的解决方法

问题描述 代码本地回滚之后&#xff08;即 git reset 到之前的某个历史节点&#xff09;&#xff0c;push上去失败&#xff0c;并报出以下错误信息 ! [rejected] master -> master (non-fast-forward) error: failed to push some refs to gitgithub.com:PisecesPeng/useg…

Strateg策略模式(组件协作)

策略模式&#xff08;组件协作&#xff09; 链接&#xff1a;策略模式实例代码 注解 目的 正常情况下&#xff0c;一个类/对象中会包含其所有可能会使用的内外方法&#xff0c;但是一般情况下&#xff0c;这些常使用的类都是由不同的父类继承、组合得来的&#xff0c;来实现…

精品Nodejs实现的校园疫情防控管理系统的设计与实现健康打卡

《[含文档PPT源码等]精品Nodejs实现的校园疫情防控管理系统的设计与实现[包运行成功]》该项目含有源码、文档、PPT、配套开发软件、软件安装教程、项目发布教程、包运行成功&#xff01; 软件开发环境及开发工具&#xff1a; 操作系统&#xff1a;Windows 10、Windows 7、Win…

【nodejs】Express概念与使用介绍

Express Express是基于Node.js平台&#xff0c;从内置模块http封装出来的第三方模块&#xff0c;可以更方便的开发Web服务器。 中文官网&#xff1a; http://www.expressjs.com.cn/ 一、基本使用 // 导入express const express require(express) // 创建web服务器 const a…

三、KMDF开发之 windbg基于网线的双机调试

目录 一 、搭建调试环境 目标机需要进入bios里面把security boot 设置为disable 1.1 网线链接 1.2 IP设置 1.2.1 关闭IPV6 1.2.2关闭防火墙 1.2.3目标机IP设置 1.2.4主机ip设置 二、设备组态 2.1 打开configure device 2.2 新增device 2.3 配置device 2.4 配置deb…

C++ Primer Plus----第十二章--类和动态内存分布

本章内容包括&#xff1a;对类成员使用动态内存分配&#xff1b;隐式和显式复制构造函数&#xff1b;隐式和显式重载赋值运算符&#xff1b;在构造函数中使用new所必须完成的工作&#xff1b;使用静态类成员&#xff1b;将定位new运算符用于对象&#xff1b;使用指向对象的指针…

IDEA中允许开启多个客户端

这个时候不要在客户端里创建socket对象时指定端口号了&#xff0c;否则会报错BindException

69内网安全-域横向CobaltStrikeSPNRDP

这节课主要讲spn和rdp协议&#xff0c; 案例一域横向移动RDP传递-Mimikatz rdp是什么&#xff0c;rdp是一个远程的链接协议&#xff0c;在linux上面就是ssh协议&#xff0c; 我们在前期信息收集的时候&#xff0c;得到一些hash值和明文密码可以进行一些相关协议的链接的&am…

python+django校园篮球论坛交流系统v5re9

本课题使用Python语言进行开发。基于web,代码层面的操作主要在PyCharm中进行&#xff0c;将系统所使用到的表以及数据存储到MySQL数据库中 技术栈 系统权限按管理员和用户这两类涉及用户划分。 (a) 管理员&#xff1b;管理员使用本系统涉到的功能主要有&#xff1a;首页、个人中…

Java Spring

目录 一、spring简介 1.1、什么是Spring 1.2 IOC 1.3、DI 二.创建Spring项目 2.1 创建一个普通的maven项目 2.2 引入maven依赖 三、Spring的创建和使用 3.1 创建Bean 3.2 将Bean放入到容器中 3.3 获取Bean对象 3.4、创建 Spring 上下文 3.5 获取指定的 Bean …

win部署stable-diffusion

win部署stable-diffusion 1.环境2.模型3.使用4.效果 1.环境 首先下载stable-diffusion-webui&#xff0c;这个包了一层ui&#xff0c;特别好用。 git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git然后搭建conda环境。 这里的pytorch&#xff0c;自己去…

挑战Python100题(8)

100+ Python challenging programming exercises 8 Question 71 Please write a program which accepts basic mathematic expression from console and print the evaluation result. 请编写一个从控制台接受基本数学表达式的程序,并打印评估结果。 Example: If the follo…

集群部署篇--Redis 哨兵模式

文章目录 前言一、哨兵模式介绍&#xff1a;1.1 介绍&#xff1a;1.2 工作机制&#xff1a; 二、哨兵模式搭建&#xff1a;2. 1 redis 主从搭建&#xff1a;2.2 setinel 集群搭建&#xff1a;2.2.1 配置&#xff1a; sentinel.conf &#xff1a;2.2.2 运行容器&#xff1a;2.2.…

提升效率:使用注解实现精简而高效的Spring开发

IOC/DI注解开发 1.0 环境准备1.1 注解开发定义bean步骤1:删除原XML配置步骤2:Dao上添加注解步骤3:配置Spring的注解包扫描步骤4&#xff1a;运行程序步骤5:Service上添加注解步骤6:运行程序知识点1:Component等 1.2 纯注解开发模式1.2.1 思路分析1.2.2 实现步骤步骤1:创建配置类…

智能硬件(8)之蜂鸣器模块

学好开源硬件&#xff0c;不仅仅需要会编程就可以了&#xff0c;电路基础是很重要的&#xff1b;软件和硬件都玩的溜&#xff0c;才是高手&#xff0c;那么小编为了方便大家的学习&#xff0c;特别画了一块智能传感器板子&#xff0c;来带领大家学习电路基础&#xff0c;玩转智…

nodejs+vue网上书城图书销售商城系统io69w

功能介绍 该系统将采用B/S结构模式&#xff0c;使用Vue和ElementUI框架搭建前端页面&#xff0c;后端使用Nodejs来搭建服务器&#xff0c;并使用MySQL&#xff0c;通过axios完成前后端的交互 系统的主要功能包括首页、个人中心、用户管理、图书类型管理、图书分类管理、图书信…

[C++] : 贪心算法专题(第一部分)

1.柠檬水找零&#xff1a; 1.思路一&#xff1a; 柠檬水找零 class Solution { public:bool lemonadeChange(vector<int>& bills) {int file0;int ten 0;for(auto num:bills){if(num 5) file;else if(num 10){if(file > 0)file--,ten;elsereturn false;}else{i…

Python生成器 (Generators in Python)

Generators in Python 文章目录 Generators in PythonIntroduction 导言贯穿全文的几句话为什么 Python 有生成器Generator&#xff1f;如何获得生成器Generator&#xff1f;1. 生成器表达式 Generator Expression2. 使用yield定义生成器Generator 更多Generator应用实例表示无…

准备用vscode代替sourceinsight

vscode版本1.85.1 有的符号&#xff0c;sourceinsight解析不到。 看网上说vscode内置了ripgrep&#xff0c;但ctrlshiftf在文件里查找的时候&#xff0c;速度特别慢&#xff0c;根本不像ripgrep的速度。ripgrep的速度是很快的。 但今天再查询&#xff0c;速度又很快了&#x…
最新文章