Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

计算程序运行时间

View previous topic View next topic Go down

计算程序运行时间

Post by too wei on December 24th 2015, 19:20

我们要怎么知道那里一个程序运行速度比较快呢?一个不错的方法就是计算程序的运行时间!

在time头文件里,定义了
clock()
返回从“程序开始运行”到“调用 clock()函数”之间的CPU时钟计时单元(clock tick)数,可以拿来除以CLOCKS_PER_SEC并得出"我们"的时间


常量CLOCKS_PER_SEC
表示一秒钟会有多少个时钟计时单元


Code:
#include<iostream>
#include<time.h>
using namespace std;

int main()
{
   clock_t start;
   clock_t finish;
   double totaltime = 0;

   start=clock();

   //任意代码。。。

   finish = clock();
   totaltime=(double)((finish-start)/CLOCKS_PER_SEC);
   cout<<"This program run "<<totaltime<<" sec"<<endl;
   return 0;
}


还有一个方法能让程序等待时间,我们把它插入在"任意代码"里

Code:
#include<iostream>
#include<time.h>
using namespace std;

int main()
{
   clock_t start;
   clock_t finish;
   double totaltime = 0;

   start=clock();

//-----------等待时间----------------
   double wait = 5 * CLOCKS_PER_SEC;
   while(clock()-start < wait); //在这里不断的循环等待时间
//-----------等待时间----------------

   finish = clock();
   totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
   cout<<"This program run "<<totaltime<<" sec"<<endl;
   return 0;
}

too wei
Sponsor
Sponsor

Posts : 31
Points : 18951
Reputation : 0
Join date : 2015-04-21
Age : 19
Location : Johor

View user profile

Back to top Go down

View previous topic View next topic Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum