C/C++的8种时间度量方式以及代码片段
liebian365 2024-10-30 04:47 27 浏览 0 评论
我们可以通过 时间度量 - Wall time vs. CPU time 来知道Wall time和CPU time的区别是什么,简单来讲,Wall Time就是类似我们的时钟一样,他没有很精确的表示此时CPU花了多少时间,而是直接用了比较粗的方式去统计。而CPU Time就比较精确的告诉了我们,CPU在执行这段指令的时候,一定消耗了多少时间。接下来我们将简单介绍8种方式来进行程序计时
如果你本身的测试程序是一个高密度的计算,比如while (10000) 内部疯狂做计算,那么你的CPU占用肯定是100%,这种情况下,你的wall time和你的CPU time其实很难区分。在这种情况下,如果你想让你的CPU idle一会的话,你可以简单的通过sleep()就可以进行实现,因为CPU在sleep()状态下是IDLE的。
1.time命令 - for Linux(Windows没有找到合适的替代品), Wall Time + CPU Time, seconds
你可以直接time你的program, 而且不需要修改你的代码,当你的程序结束运行,对应的结果会刷出来,他会同时包含wall time以及CPU time
上面的real表示wall time, user表示CPU time.同时你不需要修改你的代码。
2.#include <chrono> - for Linux & Windows(需要C++ 11),Wall Time, nanoseconds
他是度量wall time的最合适和可移植性的方法。chrono拥有你机器中的不同的clocks, 每个clock都有各自不同的目的和特征。当然除非你有特殊的要求,一般情况下你只需要high_resolution_clock.他拥有最高精度的clock,本身也应该比较实用
#include <stdio.h>
#include <chrono>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
auto begin = std::chrono::high_resolution_clock::now();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed.count() * 1e-9);
return 0;
}
可以看到,通过duration_cast我们可以把时间转换到nanoseconds,除此之外,还支持hours, minutes, seconds, millseconds, microseconds。同时需要注意的是,使用chrono库可能会比其他的C/C++方法需要损失的性能更高,尤其是在一个loop执行多次。
3.#include <sys/time.h> gettimeofday() - for Linux & Windows, Wall time,microseconds
这个函数会返回从00:00:00 UTC(1970 1.1) Epoch time. 比较tricky的一点是,这个函数会同时返回 seconds以及microseconds在不同的分别的long int变量里。所以,如果你想获取总的时间包括microseconds,你需要手动对他们做sum()
#include <stdio.h>
#include <sys/time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
struct timeval begin, end;
gettimeofday(&begin, 0);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
gettimeofday(&end, 0);
long seconds = end.tv_sec - begin.tv_sec;
long microseconds = end.tv_usec - begin.tv_usec;
double elapsed = seconds + microseconds*1e-6;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
- 如果你对小数点不感冒,你可以直接通过end.tv_sec - begin.tv_sec来获取秒级单位
- 第二个参数是用来设置当前的timezone.由于我们计算的是elapsed time, 因此timezone就没有关系
4.#include <time.h> time() - for Linux & Windows, Wall time, seconds
time()跟第三条的gettimeofday()类似,他会基于Epoch time。但是又跟gettimeofday()有两个比较大的区别:
- 你不能像gettimeofday()一样在第二个参数设置timezone,所以他始终是UTC
- 他始终只会返回full seconds
因此因为上面的第二点原因,除非你的测量精度就是seconds,否则意义不大
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
time_t begin, end;
time(&begin);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
time(&end);
time_t elapsed = end - begin;
printf("Result: %.20f\n", sum);
printf("Time measured: %ld seconds.\n", elapsed);
return 0;
}
time_t实际上就是alias long int,因此你可以直接用printf()和cout进行打印
5.#include <time.h> clock() - for Linux & Windows, CPU time on Linux, Wall time on Windows, seconds
clock()会返回在程序开始执行之后的clock ticks. 你可以通过他去除以CLOCKS_PER_SEC(在自己的Linux虚拟机测下来这个值是1000000),你会得到程序执行了多少时间(s).但是这对于不同的操作系统,行为是不一样的,比如在Linux,你得到的是CPU time,在Windows,你得到的是Wall time.因此你需要特别小心
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
clock_t start = clock();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
clock_t end = clock();
double elapsed = double(end - start)/CLOCKS_PER_SEC;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
clock_t本身也是long int, 所以当你用除法去除以CLOCKS_PER_SEC的时候,你需要先转换到double,否则你会因为整除而失去信息
6.#include <time.h> clock_gettime() - for Linux Only, Wall time / CPU time,nanoseconds
这个API是比较强大的,因为他既可以用来测Wall time又可以用来测CPU time,同时他支持nanoseconds级别。但是他唯一的不好的地方就是他只适用于Unix.你可以通过flag来控制测量wall time或者是CPU time,通过对应的CLOCK_PROCESS_CPUTIME_ID(wall time)或者CLOCK_REALTIME(CPU time)
#include <stdio.h>
#include <time.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
struct timespec begin, end;
clock_gettime(CLOCK_REALTIME, &begin);
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
clock_gettime(CLOCK_REALTIME, &end);
long seconds = end.tv_sec - begin.tv_sec;
long nanoseconds = end.tv_nsec - begin.tv_nsec;
double elapsed = seconds + nanoseconds*1e-9;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
除了CLOCK_REALTIME和CLOCK_PROCESS_CPUTIME_ID之外,你可以使用其他的clock types. 这里的timespec跟gettimeofday()的timeval很类似,但是timeval包含的是microseconds,而timespec包含的是nanoseconds
7.#include <sysinfoapi.h> GetTickCount64() - for Windows Only, milliseconds
返回当系统开机之后的millseconds毫秒个数,同样这里也有32位的版本GetTickCount(), 但是他会把时间限制在49.71 days,所以用64 bit都是比较好的
#include <stdio.h>
#include <sysinfoapi.h>
int main () {
double sum = 0;
double add = 1;
// Start measuring time
long long int begin = GetTickCount64();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
long long int end = GetTickCount64();
double elapsed = (end - begin)*1e-3;
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
8.#include <processthreadsapi.h> GetProcessTimes() - for Windows Only(但是这时唯一可以在Windows上测量CPU time的方法), CPU time
原理本身比较复杂,如果有兴趣可以自己找资料继续阅读
#include <stdio.h>
#include <processthreadsapi.h>
double get_cpu_time(){
FILETIME a,b,c,d;
if (GetProcessTimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}else{
// Handle error
return 0;
}
}
int main () {
double sum = 0;
double add = 1;
// Start measuring time
double begin = get_cpu_time();
int iterations = 1000*1000*1000;
for (int i=0; i<iterations; i++) {
sum += add;
add /= 2.0;
}
// Stop measuring time and calculate the elapsed time
double end = get_cpu_time();
double elapsed = (end - begin);
printf("Result: %.20f\n", sum);
printf("Time measured: %.3f seconds.\n", elapsed);
return 0;
}
网上有人基于这个工具提供了同时计算CPU time以及wall time的方法, 有兴趣的话可以自己去进行进一步学习
相关推荐
- 精品博文嵌入式6410中蓝牙的使用
-
BluetoothUSB适配器拥有一个BluetoothCSR芯片组,并使用USB传输器来传输HCI数据分组。因此,LinuxUSB层、BlueZUSB传输器驱动程序以及B...
- win10跟这台计算机连接的前一个usb设备工作不正常怎么办?
-
前几天小编闲来无事就跑到网站底下查看粉丝朋友给小编我留言询问的问题,还真的就给小编看到一个问题,那就是win10跟这台计算机连接的一个usb设备运行不正常怎么办,其实这个问题的解决方法时十分简单的,接...
- 制作成本上千元的键盘,厉害在哪?
-
这是稚晖君亲自写的开源资料!下方超长超详细教程预警!!全文导航:项目简介、项目原理说明、硬件说明、软件说明项目简介瀚文智能键盘是一把我为自己设计的——多功能、模块化机械键盘。键盘使用模块化设计。左侧的...
- E-Marker芯片,USB数据线的“性能中枢”?
-
根据线缆行业的研究数据,在2019年搭载Type-C接口的设备出货量已达到20亿台,其中80%的笔记本电脑和台式电脑采用Type-C接口,50%的智能手机和平板电脑也使用Type-C接口。我们都知道,...
- ZQWL-USBCANFD二次开发通讯协议V1.04
-
修订历史:1.功能介绍1.1型号说明本文档适用以下型号: ZQWL-CAN(FD)系列产品,USB通讯采用CDC类实现,可以在PC机上虚拟出一个串口,串口参数N,8,1格式,波特率可以根据需要设置(...
- win10系统无法识别usb设备怎么办(win10不能识别usb)
-
从驱动入手,那么win10系统无法识别usb设备怎么办呢?今天就为大家分享win10系统无法识别usb设备的解决方法。1、右键选择设备管理器,如图: 2、点击更新驱动程序,如图: 3、选择浏览...
- 微软七月Win8.1可选补丁有内涵,含大量修复
-
IT之家(www.ithome.com):微软七月Win8.1可选补丁有内涵,含大量修复昨日,微软如期为Win7、Win8.1发布7月份安全更新,累计为6枚安全补丁,分别修复总计29枚安全漏洞,其中2...
- 如何从零开始做一个 USB 键盘?(怎么制作usb)
-
分两种情况:1、做一个真正的USB键盘,这种设计基本上不涉及大量的软件编码。2、做一个模拟的USB键盘,实际上可以没有按键功能,这种的需要考虑大量的软件编码,实际上是一个单片机。第一种设计:买现成的U...
- 电脑识别U盘失败?5个实用小技巧,让你轻松搞定USB识别难题
-
电脑识别U盘失败?5个实用小技巧,让你轻松搞定USB识别难题注意:有些方法会清除USB设备里的数据,请谨慎操作,如果不想丢失数据,可以先连接到其他电脑,看能否将数据复制出来,或者用一些数据恢复软件去扫...
- 未知usb设备设备描述符请求失败怎么解决
-
出现未知daousb设备设备描述符请求失du败解决办zhi法如下:1、按下Windows+R打开【运行】;2、在版本运行的权限输入框中输入:services.msc按下回车键打开【服务】;2、在服务...
- 读《飘》47章20(飘每章概括)
-
AndAhwouldn'tleaveMissEllen'sgrandchildrenfornotrashystep-patobringup,never.Here,Ah...
- 英翻中 消失的过去 37(消失的英文怎么说?)
-
翻译(三十七):消失的过去/茱迪o皮考特VanishingActs/JodiPicoult”我能做什么?“直到听到了狄利亚轻柔的声音,我才意识到她已经在厨房里站了好一会儿了。当她说话的时候,...
- RabbitMQ 延迟消息实战(rabbitmq如何保证消息不被重复消费)
-
现实生活中有一些场景需要延迟或在特定时间发送消息,例如智能热水器需要30分钟后打开,未支付的订单或发送短信、电子邮件和推送通知下午2:00开始的促销活动。RabbitMQ本身没有直接支持延迟...
- Java对象拷贝原理剖析及最佳实践(java对象拷贝方法)
-
作者:宁海翔1前言对象拷贝,是我们在开发过程中,绕不开的过程,既存在于Po、Dto、Do、Vo各个表现层数据的转换,也存在于系统交互如序列化、反序列化。Java对象拷贝分为深拷贝和浅拷贝,目前常用的...
- 如何将 Qt 3D 渲染与 Qt Quick 2D 元素结合创建太阳系行星元素?
-
Qt组件推荐:QtitanRibbon:遵循MicrosoftRibbonUIParadigmforQt技术的RibbonUI组件,致力于为Windows、Linux和MacOSX提...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)