您的位置:首页 > 其它

算法时间测试

2016-07-14 23:23 183 查看
//算法时间测试 基准法(定量分析) 大O法(定性分析)
//以下是基准法
#include "iostream"
#include "cstdio"
#include "ctime"
#include "windows.h"
using namespace std;
int main()
{
//法一
clock_t start1,end1;//clock_t  需头文件#include "ctime"
double duration1 ;

start1=clock();//返回程序运行到此位置时所用毫秒数
::Sleep(3000);//延时函数 参数为毫秒  头文件#include "windows.h"   注俩冒号和大写S
end1=clock();
duration1=(double)(end1-start1)/CLOCKS_PER_SEC;//为输出秒,毫秒化秒
cout<<"The clock_t  time is  "<<duration1<<"S"<<endl;

//法二
time_t start2,end2;

start2=time(0);//获取的是从1970 1 1 0:0:0 到现在的秒数(注意单位为秒)
::Sleep(3000);
end2=time(0);
double duration2=end2-start2;
cout<<"The time_t   time is  "<<duration2<<"S"<<endl;
}
View Code

 感谢http://blog.csdn.net/theprinceofelf/article/details/6636041

这个是针对于特定的平台的测试,有时候我们需更高的精度测试时,往往需要用到这个测试
<Windows.h>版本
#include "windows.h"
int main()
{
LARGE_INTEGER frec;//记录CPU每秒频率
LARGE_INTEGER strt;
LARGE_INTEGER ed;
QueryPerformanceFrequency(&frec);///查询频率
QueryPerformanceCounter(&strt);///测开始处的时钟数
::Sleep(3000);
QueryPerformanceCounter(&ed);///测结束处的时钟数
cout<<(ed.QuadPart-strt.QuadPart)*1000000/frec.QuadPart<<"us"<<endl;///相减除以每秒的频率
///。*1是秒数,*1000是毫秒数,*1000 000 是微妙数,*1000 000 000是ns数。
}

 好的代码习惯:测试代码 -->  伪代码 --> 实际代码 --> 更加高效的版本 --> 带输入输出控制检测,出错验证的代码  -->更加灵活的版本

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: