C++测试/获取代码执行时间

Window系统下C/C++程序毫秒级和微秒级执行时间获取方法 阅读详情

C++ 高级之程序执行时间监听

C++测试/获取代码执行时间(clock方法与dword 方法的区别)

方法一:Clock

clock()捕捉从程序开始运行到clock()被调用时所耗费的时间,这个单位是常熟CLK_TCK:机器时钟每秒所走的时钟打点数

头部需要引入ctime头文件(即:#include<ctime>)
clock_t startTime,endTime;
startTime = clock();
需要测试的程序代码
endTime = clock();

执行结果
在这里插入图片描述

方法二:GetTickCount

GetTickCount是一种函数,GetTickCount返回从操作系统启动所经过的毫秒数,它的返回值是DWORD,
详细解释(GetTickcount函数:它返回从操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是(2^32-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0,MSDN中也明确的提到了:“Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.”。因此,如果是编写服务器端程序,此处一定要万分注意,避免引起意外的状况)

int main()
{
DWORD dwStart = GetTickCount();
cout<<"fhshdfudshfuisdhfdshfdsfdshfiuhsdihfiudshfhsdlihfdis"<<endl;
DWORD dwEnd =GetTickCount();
cout << "The run time is: " <<dwEnd - dwStart / CLOCKS_PER_SEC << "ms" << endl;
getchar();
return 0;
}

执行结果

在这里插入图片描述

CLOCK与GetTickCount各自的优缺点和区别:

**clock:**程序中经常用time()函数来返回当前系统时间的秒数,来计时或计算时间差。如果需要用到更高精度的时间,就会自然想到用clock()函数。想当然的认为它返回从程序开始tick数,用clock()/CLOCKS_PER_SEC就能得到以秒计数的时间了。然而结果不是这样,看下面的程序log。一行开头是系统时间,后面是clock()算出来的,明显比系统时间要慢不少,也就是说clock计算执行时间的误差较大
GetTickCount: 在要求误差不大于1毫秒的情况下,可以采用GetTickCount()函数,该函数的返回值是DWORD型,表示以毫秒为单位的计算机启动后经历的时间间隔。使用下面的编程语句,可以实现50毫秒的精确定时,其误差小于1毫秒。
对于一般的实时控制
,使用GetTickCount()函数就可以满足精度要求,但要进一步提高计时精度,就要采用QueryPerformanceFrequency()函数和QueryPerformanceCounter()函数。这两个函数是VC提供的仅供Windows 9X使用的高精度时间函数,并要求计算机从硬件上支持高精度计时器。QueryPerformanceFrequency()函数和QueryPerformanceCounter()函数的原型为:
BOOL QueryPerformanceFrequency(LARGE—INTEGER *lpFrequency);
BOOL QueryPerformanceCounter(LARGE—INTEGER *lpCount) ;

测试c++程序运行时间代码 在runtime.h里有个计算程序运行时间的代码,精确到毫秒 立即下载

相关推荐

Vue+ECharts-GL 3D地图实战:5层叠加打造炫酷中国地图(附完整代码)

本文详细介绍了如何利用Vue和ECharts-GL构建具有强烈立体感的3D中国地图。通过5层图层的巧妙叠加与样式调校,实现了从背景阴影到交互高光的完整视觉层次,并整合了动态飞线与散点标记。文章提供了完整的代码实现、核心配置解析以及性能优化与视觉调优的实战技巧,帮助开发者快速打造专业级的交互式地图可视化应用。

d6e7f8g9h的博客 651

C++输出代码的运行时间

参考:https://www.cnblogs.com/apebro/p/12581417.html #include<stdio.h> #include<time> printf("Time used = %.2f\n", (double)clock() / CLOCKS_PER_SEC); printf输出的时间是以秒为单位; 常数CLOCKS_PER_SEC是和操作系统相关,不要直接使用clock()获取的运行时间返回值,应除以CLOCKS_PER_SEC; #include

GXQ的博客 5734

手把手教你设计T型和Π型衰减器:从分贝计算到电阻选型全攻略

本文提供了一份T型和Π型衰减器的详细设计指南,涵盖从分贝计算到电阻选型的全过程。文章以50欧姆系统为例,通过公式推导和实例演示,手把手教你计算两种经典拓扑的电阻值,并深入探讨了电阻选型、误差控制及高频应用等关键实践技巧,帮助工程师和爱好者精准实现信号衰减与阻抗匹配。

blue42的博客 1337

C++获取代码运行时间

C++获取代码运行时间 在程序运行中经常需要计算某一段代码的执行时间,如何获取代码的运行时间在调试中,下面给出两种常用的方式:   第一种:使用GetTickCount函数   #include #include using namespace std;   int main() {    DWORD start_time=GetTickCount();

lj_suxin的专栏 876

STM32HAL库 基于外部Flash+FatFs模拟U盘方式进行固件拷贝升级(详解)

STM32HAL库 基于外部Flash+FatFs模拟U盘方式进行固件拷贝升级

qq_36075612的博客 1万+

TMS320F28377D的sys/bios双核工程配置详解——从零搭建到RAM优化

本文详细解析了TMS320F28377D双核系统在sys/bios环境下的工程配置与RAM优化策略。从开发环境搭建、SYS/BIOS工程创建到双核CMD文件配置,提供了实战技巧和常见问题解决方案,帮助开发者高效实现电力电子控制系统中的双核协作与性能优化。

weixin_28292761的博客 600

C/C++工具类快速输出函数运行时间方便优化和查找问题

平常想输出一下函数的运行时间都是这么做的: void fuction Test() { clock_t start = clock(); do somthing... cout << clock() - start ; } 后来觉得这些重复的操作是在没有必要,想弄个更方便的,于是就有了下面这个类 #include <stdio.h> #include <iostream> #include<ctime> using namesp

猫叔压力大 1366

Windows平台无人机仿真:从零搭建SITL环境与QGC联调

本文详细指导了在Windows平台上从零搭建无人机软件在环(SITL)仿真环境,并与QGroundControl(QGC)进行联调的完整流程。通过使用Cygwin工具链,开发者可以在没有实体硬件的情况下,模拟运行ArduPilot飞控,并通过MAVLink协议连接QGC地面站进行全功能测试,为无人机软件开发提供了一个安全、经济的虚拟沙盒环境。

weixin_29239279的博客 411

C++计算打印函数和代码块的执行时间(支持所有类型函数)

所以本文对此方法进行优化,通过万能引用 + 变长参数模板 + std::future 实现支持对 携带任意参数和返回值的函数进行测量。对于绝大部分情况,这种方式是足够了,但是缺陷也很明显:measure函数不支持带有参数的函数,而且无法打印函数的返回值。》讲述了一种衡量线程执行时间的方法。

崔杰城的博客 1865

【EB_Tresos专题】-06-配置一个UDS诊断DID

<--返回「Autosar_BSW高阶配置」总目录--> <--返回「Autosar_BSW高阶配置」专栏主页--> <--返回「个人博客」首页--> <--返回「Autosar_BSW高阶配置」总目录--> <--返回「Autosar_BSW高阶配置」专栏主页--> <--返回「个人博客」首页--> 结尾 ...

「汽车电子助手」的博客 4087

UniRx之基本语法格式

想要更好的去学习UniRx,我们最好是先理解UniRx 的语法格式。就像我们去学习英语或者汉语一样,理解了基本的语法规则后,再学其他的就信手拈来了。

TxNet 924

C++ 获取程序运行时间

C++ 获取程序运行时间

Where there is life, there is hope. 4326

YOLOv8【第十一章:视频追踪与流处理篇·第3节】匈牙利算法(Hungarian Algorithm)与 KM 算法匹配机制详解!

🏆 本文收录于 《YOLOv8实战:从入门到深度优化》 专栏。该专栏系统复现并梳理全网各类 YOLOv8 改进与实战案例(当前已覆盖分类 / 检测 / 分割 / 追踪 / 关键点 / OBB 检测等方向),坚持持续更新 + 深度解析,质量分长期稳定在 97 分以上,可视为当前市面上 覆盖较全、更新较快、实战导向极强 的 YOLO 改进系列内容之一。

**My Coding Family** 445

PPPwn_cpp终极指南:如何通过C++重写实现PlayStation 4远程代码执行

PPPwn_cpp是一个基于C++重写的PlayStation 4 PPPoE远程代码执行漏洞利用工具,它为安全研究人员和游戏机爱好者提供了一个强大而高效的安全研究平台。通过优化性能和跨平台支持,这个项目将原始的Python实现转化为更快速、更稳定的C++版本,让PS4安全研究变得更加简单和可靠。无论你是想要探索游戏机安全漏洞的开发者,还是对系统安全感兴趣的研究者,PPPwn_cpp都能为你提供完

gitblog_00022的博客 997

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

c/c++在windows下获取时间和计算时间差的几种方法总结

c/c++在windows下获取时间和计算时间差的几种方法总结 (转自http://blog.youkuaiyun.com/coder_xia/article/details/6566708) 一、标准C和C++都可用 1、获取时间用time_t time( time_t * timer ),计算时间差使用double difftime( time_t timer1, time_...

weixin_30677475的博客 2661

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

C/C++获取当前系统毫秒时间

Java获取当前系统毫秒时间很简单: public static void main(String[] args){ System.out.println("java program :" + System.currentTimeMillis()); } C/C++稍微复杂一点,要借助timeval,至于timeval的详细说明,只需google一下就明了...

qq_23350817的博客 8041

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

终极指南:如何使用PPPwn_cpp实现PlayStation 4远程代码执行

PlayStation 4远程代码执行漏洞利用工具PPPwn_cpp是一个基于C++重写的强大工具,专为安全研究者和游戏开发者设计。这个工具利用了PS4系统PPPoE协议中的漏洞,实现了内核级远程代码执行功能。无论你是想深入了解游戏机安全机制,还是需要在自己的PS4上进行自定义开发,PPPwn_cpp都能为你提供完整的解决方案。 ## 为什么选择PPPwn_cpp进行PS4漏洞利用? PPPw

gitblog_00812的博客 1062

C/C++获取当前系统毫秒时间戳

C/C++获取当前系统毫秒时间 由于要实现与JAVA相同的功能,所以先贴上JAVA代码的实现: public static void main(String[] args){ System.out.println("java program :" + System.currentTimeMillis()); } 起初准备采用time(NULL)来实现...

FeelTouch Labs 5721

c/c++获取时间和计算时间差的几种方法总结

一、标准C和C++都可用 1、获取时间用time_t time( time_t * timer ),计算时间差使用double difftime( time_t timer1, time_t timer0 )。 精确到秒。 测试程序如下: [c-sharp] view plaincopy #include   #include   int main()  {      ti

keleigexiansheng的专栏 2万+

[C/C++]C/C++计算代码的运行时间

有很多时候,实现一个功能后可能不仅仅要效果,还要效率,如果可以在极短的时间内完成一个功能那当然是最好不过的啦,但是可能经常会事与愿违。 这里就写一下,都可以怎样用C/C++或者Qt的方法来测试代码的运行时间。 一、C/C++方法 1.1 clock_t方法 clock_t方法需要包含头文件<time.h>,clock_t是一个长整型数字,它可以将时间精确到毫秒级别: #in...

上善若水,为而不争 824

c和c++在windows下获取时间和计算时间差的方法总结

c/c++在windows下获取时间和计算时间差的几种方法总结 一、标准C和C++都可用 1、获取时间用time_t time( time_t * timer ),计算时间差使用double difftime( time_t timer1, time_t timer0 )。 精确到秒。 测试程序如下:  1 #include <time.h> 2 #include <stdio.h> 3 4 int main() 5 { 6 time_t star.

qq_38883139的博客 3677

C++统计代码执行耗时

C++统计代码执行耗时

Erice_s的博客 2878

5分钟掌握Catch2性能测试:让你的C++代码执行时间一目了然

在C++开发中,你是否曾遇到过这样的困扰:明明通过了单元测试的代码,在实际运行时却慢得让人难以忍受?如何精准测量代码执行时间,找出性能瓶颈?本文将带你快速掌握Catch2测试框架的性能测试功能,用简单几步实现代码执行时间的精准统计,让你的C++程序跑得又快又稳。 读完本文后,你将能够: - 理解Catch2性能测试的核心概念与执行流程 - 使用基础`BENCHMARK`宏快速实现函数执行时间统计...

gitblog_00333的博客 1036

不同编程语言如何统计代码执行时间

通过上述示例,你可以看到不同编程语言提供了多种方法来测量代码执行时间。选择哪种方法取决于具体的需求,比如是否需要高精度的测量结果、是否需要考虑CPU时间还是墙钟时间等。在实际应用中,根据具体情况选择合适的方法来统计代码执行时间,可以帮助开发者更好地优化程序性能。

极客代码 1608
下一篇: 【React Native 运行报:Dependency requires at least JVM runtime version 11. This build uses a Java 8 JVM】
菜鸟醒醒
博客等级 码龄7年 59粉丝 5原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值