C/C++程序计时函数

总结一下C/C++程序中几种常用的计时函数 在编写程序时,有时需要准确测量一个算法的运行时间,以做到对某一特定的数据集,不同算法耗时的比较。 题主今天在编写算法课实验代码的时候,大致在网上搜索了下C/C++中几种常用的计时函数,在此做一个总结,希望对大家学习C/C++以及算法有所帮助。 // Windows系统下可以用 time(),clock(),timeGetTime(),GetTickCount(), // QueryPer 阅读详情

在C/C++中有可以直接测试程序运行时间的函数,在<time.h>/<ctime>头文件中,非常方便和实用。

clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下:
clock_t clock(void) ;
简单而言,就是该程序从启动到函数调用占用CPU的时间。这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock);若挂钟时间不可取,则返回-1。其中clock_t是用来保存时间的数据类型,clock_t实质是头文件中long数据类型类型定义的一个代称。使用计时很简单,只要在程序想计时的地方放入一个clock()函数,另外在结束地方放置一个clock()函数,两个返回值的差即是程序消耗时间。但是该函数计时是以毫秒(ms)为单位的,也就是没过千分之一秒加一,所以需要除以一个常量1000才是以秒计时的,一般使用头文件中声明好的常量CLOCKS_PRE_SEC(即1000)。

测试程序如下:

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
clock_t start,end;

int main(){
	start=clock();		//程序开始计时
	int ans=0;
	for(int i=1;i<=1e8;i++)
		ans++;
	end=clock();		//程序结束用时
	double endtime=(double)(end-start)/CLOCKS_PER_SEC;
	cout<<"Total time:"<<endtime<<endl;		//s为单位
	cout<<"Total time:"<<endtime*1000<<"ms"<<endl;	//ms为单位
	system("pause");
	return 0;
}

运行截图:


用double强转是为了更精确,不然不足1秒的会显示0s。
C++执行程序计时函数详解 通常计时函数主要有两个,分别是getTickCount()和getTickFrequency(). 阅读详情

相关推荐

Synares病毒实战:如何从U盘感染中恢复你的Excel和EXE文件(附专杀工具推荐)

本文详细介绍了Synares感染型病毒的典型特征与传播机制,特别是其通过U盘感染Excel和EXE文件的行为。文章提供了一套从应急隔离、诊断到使用专杀工具进行深度清除与文件恢复的完整实战流程,并推荐了有效的安全软件和修复方法,旨在帮助用户最大程度救回重要数据并构建长效安全防护习惯。

weixin_29230649的博客 1881

获取系统时间几种方法 和 使用CPU时间戳进行高精度计时

1 使用time_t time( time_t * timer )    精确到秒  计算时间差使用double difftime( time_t timer1, time_t timer0 )2 使用clock_t clock() 得到的是CPU时间    精确到1/CLOCKS_PER_SEC秒3 使用DWORD GetTickCount() 得到的是系统运行的时间 精确到毫秒4

KEN Bolg 5508

告别双系统!用PhyFusion在麒麟V10上无缝融合Win11,文件互传、GPU加速全搞定

本文详细介绍了在飞腾D3000平台上使用PhyFusion实现麒麟V10与Win11无缝融合的解决方案。通过视觉无界、数据互通和性能无损的三大突破,PhyFusion显著提升了跨系统工作效率,支持GPU加速和文件互传,是国产化平台的革命性工具。

weixin_28707365的博客 1042

C++获取程序运行时间

C++中的计时函数是clock(),而与其相关的数据类型是clock_t(头文件是time.h)。函数定义原型为:clock_t clock(void);   这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。   其中clock_t是用来保存时间的数据类型,在ti

小粪球的专栏 2124

深度学习&故障诊断初学者 - 学习路线

针对初学者,一头雾水,不知如何学习,本文给出了一个学习路线 Python学习 - 打好编程基础 https://www.bilibili.com/video/BV1vA411b7Rn?spm_id_from=333.337.search-card.all.click B站免费课程 学到P49 建议时长 2周 深度学习理论 - 浅浅理解神经网络 https://www.bilibili.com/video/BV1FT4y1E74V?p=41 建议时长 2周...............

m0_47410750的博客 6万+

【win11 cuda12.0安装tensorflow-gpu】

win11 cuda 12.0 安装 tensorflow-gpu

weixin_36299320的博客 3014

C++里的clock()函数介绍

c++的头文件ctime中的库函数clock()clock()返回类型为clock_t类型clock_t实际为long类型,即clock()函数,返回从开启这个程序进程到程序中调用clock()函数时之间的CPU时钟计时单元(clock tick)数(挂钟时间),返回单位是毫秒可以用常量, 这个常量表示每一秒(per second)有多少个时钟计时单元。

eternity6666的博客 1万+

ABAQUS应用15——Abaqus软件中边界条件与力学中自由度的关系

核心关系:Abaqus通过约束自由度实现边界条件,自由度类型由单元决定。正确设置步骤:确定模型类型(实体/梁/壳)。识别节点的自由度(平动或转动)。根据实际约束施加对应的自由度限制。验证:通过检查变形模式、反力分布等确认边界条件合理性。正确理解自由度与边界条件的关系,是确保有限元模型准确模拟实际物理行为的关键。

George的博客 1553

c++中的clock()函数

文章目录前言主要函数clock()函数 前言 今天刷PAT时,写到人口普查这个题,以前使用的字符串处理.现在就想着能不能用关于时间的函数处理,遂学习了一下关于时间的函数. 主要函数 clock()函数 头文件:#include<time.h>或者#include<ctime> 作用:返回处理器调用某个进程或函数所花费的时间。函数返回从“开启这个程序进程”到“程序中调用clo...

weixin_43725617的博客 8461

《民机适航入门指南:从法规学习到项目实践的全面解析》

适航(Airworthiness)是指航空器、其发动机、螺旋桨和其他部件在规定条件下,能够安全飞行并满足有关航空法规规定的条件。简而言之,适航代表了航空器在任何时候都能安全运营的状态。适航在民用航空领域尤为关键,因为飞机必须经过严格的适航认证才能投入商用。这些认证的目标是确保飞机能够在广泛的运行条件下保持飞行安全,从而保护乘客、机组和地面人员的生命财产安全。适航法规覆盖了飞机的整个生命周期,包括设计、制造、测试、运营、维护和报废。

qq_41854911的博客 996

模型瘦身术:YOLOv5无损剪枝实战教程

本文介绍了一种YOLOv5模型的无损剪枝方法,通过"稀疏训练+结构化剪枝+微调"的流程,在不损失精度的前提下显著减小模型尺寸并提升推理速度。具体步骤包括:1)稀疏训练给参数排优先级;2)裁剪不重要通道;3)微调恢复精度;4)验证效果。实战部分详细展示了从环境搭建到剪枝实现的完整流程,并分析了剪枝后在边缘设备部署、实时检测等场景的优势。该方法可使YOLOv5s模型从14MB缩减至2-3MB,推理速度提升30%-50%,适用于资源受限设备的轻量化部署需求。

LXY_LOVE36的博客 110

C/C++ 程序计时函数

//clock() 记录此刻时间,差值计算程序用时 #include<iostream> #include<cstdlib> #include<ctime> //头文件 using namespace std; clock_t t_start,t_end; int main(){ t_start=clock(); //程序开始计时 int ans=1e8; while(ans>0){ ans--; } t_end=clock(); //程

0 437

Codex 100个真实案例 - 用AI画业务流程图Mermaid(产品经理都馋哭了)

还在用 Visio、ProcessOn 拖拖拽拽画流程图?改一个箭头方向就要调半天?本案例教你用 Codex 自然语言描述业务流程,AI 自动转为 Mermaid 代码,一秒生成专业流程图、时序图、甘特图、饼图!还能搭建在线渲染工具、批量导出 PNG/SVG、集成到文档系统。产品经理、架构师、项目经理都能用,从此画图再也不是体力活!

yueyeguzhuo的专栏 367

c++ clock单位_C/C++程序计时

功能介绍clock()是C/C++中的计时函数这个函数计算的是程序从启动到函数调用占用CPU的时间。这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元数.在程序想要开始计时的地方放入一个clock()函数,另外在想要结束计时地方放一个clock()函数,两个返回值的差即是程序消耗时间。这个函数计时是以ms为单位的,但是一般会用s为单位计...

weixin_35795675的博客 3059

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

C/C++程序计时函数gettimeofday的使用

linux 环境下 用 clock_t发现不准。 换用 //头文件 #include <sys/time.h> //使用timeval start, end; gettimeofday(&start, NULL); sleep(3); gettimeofday(&end, NULL); cout << 1000*(end.tv...

weixin_30764771的博客 395

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

C/C++ 各种计时函数总结

C/C++ 各种计时函数总结

bizhu的专栏 990

深度学习工具包 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")

关于clock()函数计时

<br />     clock tick:时钟计时单元(而不把它叫做时钟滴答次数),一个时钟计时单元的时间长短是由CPU控制的,<br />     一个clock tick不是CPU的一个时钟周期,而是C/C++的一个基本计时单位。<br /> <br />     clock函数:clock_t clock(); 这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间<br />     的CPU时钟计时单元 (clock tick)数,在MSDN中称之为挂钟时间(wal-cloc

roma823的专栏 1万+

c语言中得出程序运行时间,C语言计算程序运行时间?

程序代码: 运行结果: C/C++中的计时函数是clock(),而与其相关的数据类型是clock_t。clock函数定义如下:clock_tclock(void);这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clocktick)数,在MSDN中称之为挂钟时间(wal-clock)。其中clock_t是用来保存时间的数据类型,在ti...

weixin_32328999的博客 3138

C/C++/Java 程序计时功能函数

编写程序肯定要使用计时功能,来判断程序的执行时间。今天Google了一下,自己就梳理总结一下: (1)C/C++程序计时   C/C++中使用的计时函数是clock()。   C语言中的头文件对应是#include<time.h>,C++中对应的头文件为#include<ctime>。   如下程序实例,其中clock_t为long类型,CLOCKS_PER_SEC...

weixin_34187862的博客 84

C++ 统计程序运行耗时的几种方法的总结

方法一 利用GetTickCount函数(ms) 代码: CString str;            longt1=GetTickCount();//程序段开始前取得系统运行时间(ms)             。。。。。。//to do sth longt2=GetTickCount();//程序段结束后取得系统运行时间(ms)         str.F

cai_huan_123的专栏 1万+

C/C++中的计时函数

C/C++中的计时函数是clock(),而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下: clock_t clock( void ); 这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wall-clock)。其中clock_t是用来保存时间的数据类型,在tim

selinahuiling的专栏 1438

c++计时函数

在C/C++中有可以直接测试程序运行时间的函数,在<time.h>/<ctime>头文件中,非常方便和实用。 clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下: clock_t clock(void) ; 简单而言,就是该程序从启动到函数调用占用CPU的时间。这个函数返回从“开启这个程序进程”到“程序中...

weixin_50792396的博客 561

C/C++中如何精确计时

给程序计时对于程序员来说实在是太重要了,在windows上的那个clock()实在是不够精确,精度只有10ms,真让人难过。研究了下windows下使用C、C++计时的函数,给大家分享下。 主要就是两个函数的使用。我先把一段可以运行的代码贴出来,然后讲讲这两个函数。 #include #include int main(int argc, char **argv) { LARGE_INT

Expressing Youself Using Code 1万+

c语言窗口程序暂停,C语言中的时间和程序暂停

C/C++中的计时函数是clock(),而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下:clock_t clock( void );这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。其中clock_t是用来保存时间的数据类型,在time.h文件...

weixin_30129661的博客 4807
上一篇: Codeforces Round #478 (Div. 2) B. Mancala
下一篇: vim配置C/C++,java,python运行环境
_dingzhen
博客等级 码龄9年 120粉丝 44原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址