如何在C++程序中添加计时器判断两个函数的运行时间长短

 我来答
中大heartrain
推荐于2017-10-07 · TA获得超过263个赞
知道答主
回答量:57
采纳率:0%
帮助的人:82万
展开全部
#include <ctime>
#include <iostream>
using namespace std;

int main () {
clock_t start, finish; //typedef long clock_t;
double totaltime;
start = clock(); //clock():Current time of CPU

for (int i = 0; i < 1000000; i++)
{
}

finish=clock();
totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<"\nRuntime is: " << totaltime << "s" << endl;
return 0;
}

中间位置是你需要测试的函数,为简便我只写了一个for循环~
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
帐号已注销
2016-01-09 · 超过87用户采纳过TA的回答
知道小有建树答主
回答量:204
采纳率:0%
帮助的人:120万
展开全部
获取机器时钟。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
在老君观喝啤酒的金鱼草
2010-12-04 · TA获得超过257个赞
知道小有建树答主
回答量:110
采纳率:0%
帮助的人:131万
展开全部
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void sleep( clock_t wait );

void main( void )
{
long i = 600000L;
clock_t start, finish;
double duration;

/* Delay for a specified time. */
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );

/* Measure the duration of an event. */
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.1f seconds\n", duration );
}

/* Pauses for a specified number of milliseconds. */
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}

If you have another problems,you may call me.
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
lovemezhoupeng
2010-12-04 · TA获得超过1187个赞
知道小有建树答主
回答量:269
采纳率:0%
帮助的人:0
展开全部
#include <windows.h>
#include <stdio.h>
#include <time.h>

typedef long ClockT;

ClockT start;
ClockT finish;
double dtime;

int main ()
{
//开始计时保存到start
start=clock();

//具体运算
Sleep(1900);

//结束计时保存到finish
finish=clock();

dtime=(double)(finish-start);
printf("精确时间: %lf\n",dtime);
printf("一般时间: %lf\n",dtime/CLOCKS_PER_SEC);
return 0;
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 1条折叠回答
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式