【转】C/C++中 算法运行时间的三种计算方式

本文转自: http://www.cnblogs.com/zxher/archive/2010/10/25/1860118.html

算法执行时间需通过依据该算法编制的程序在计算机上运行时所消耗的时间来度量。而度量一个程序的执行时间通常有两种方法。

  • 事后统计的方法:该方法利用计算机内部的计时功能,可以精确到毫秒级别,这种方法有两个缺点:一是必须依据算法先编写好程序;二是运行程序的软硬件环境易喧宾夺主,掩盖算法本身的优劣。但是有时候在同一台机器上,想对不同算法进行比较或是想知道一个程序究竟需要运行多长时间,该方法就有了用武之地了。本文主要介绍三种事后计算算法运行时间的方式,具体的可以参见源代码,即time_t/time、timeb/ftime、clock/CLOCKS_PER_SEC。
  • 事前分析的方法:该方法考虑如下因素(a)算法选用策略;(b)问题规模;(c)书写程序的语言级别;(d)编译程序产生机器代码质量;(e)机器执行指令的速度。然后对算法进行大O分析。此方法不在本文讨论范围之内。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
#include <stdio.h> #include <tchar.h> #include <cstdlib> #include <iostream> #include <sys/timeb.h> #include <ctime> #include <climits> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { //计时方式一 time_t start = 0,end = 0; time(&start); for(int i=0; i < numeric_limits<int>::max(); i++) { double circle = 3.1415962*i; //浮点运算比较耗时,循环最大整数次数 } time(&end); cout << "采用计时方式一(精确到秒):循环语句运行了:" << (end-start) << "" << endl; //计时方式二 struct timeb startTime , endTime; ftime(&startTime); for(int i=0; i < numeric_limits<int>::max(); i++) { double circle = 3.1415962*i; //浮点运算比较耗时,循环最大整数次数 } ftime(&endTime); cout << "采用计时方式二(精确到毫秒):循环语句运行了:" << (endTime.time-startTime.time)*1000 + (endTime.millitm - startTime.millitm) << "毫秒" << endl; //计时方式三 clock_t startCTime , endCTime; startCTime = clock(); //clock函数返回CPU时钟计时单元(clock tick)数,还有一个常量表示一秒钟有多少个时钟计时单元,可以用clock()/CLOCKS_PER_SEC来求取时间 for(int i=0; i < numeric_limits<int>::max(); i++) { double circle = 3.1415962*i; //浮点运算比较耗时,循环最大整数次数 } endCTime = clock(); cout << "采用计时方式三(好像有些延迟,精确到秒):循环语句运行了:" << double((endCTime-startCTime)/CLOCKS_PER_SEC) << "" << endl; cout << "综合比较上述三种种计时方式,方式二能够精确到毫秒级别,比方式一和三都较好。此外在Windows API中还有其他的计时函数,用法都大同小异,在此就不做介绍了。" << endl; system("pause"); return 0; }

 对于计时方式二,可以精确到毫秒级,要熟练掌握并运用。

#include <sys/timeb.h>

struct timeb startTime, endTime;
ftime(&startTime);
....
ftime(&endTime);
(endTime.time - startTime.time)*1000 + (endTime.millitm - startTime.millitm)
原文地址:https://www.cnblogs.com/wenshanzh/p/2790340.html