C++实现测试函数运行时间函数

使用方法:

gettime(函数名,[要测试函数的参数,在0~3个范围内],时间单位)
// 时间单位如果不写,默认为毫秒。
// 时间单位的格式:
//     ns  纳秒
//     us  微秒
//     ms  毫秒
//     s   秒
//     min 分钟
//     h   小时
//     d   天

具体实现(注:Windows系统):

//gettime.h
#ifndef GETTIME_H
#define GETTIME_H
#include<ctime>
using namespace std;
#define FUNCTION_CODE(func_sentence)\
	clock_t start,finish;\
	start=clock();\
	func_sentence;\
	finish=clock();\
	LONGEST_FLOAT sec_divide=1e-3;\
	if(unit=="ns") sec_divide=1e-9;\
	else if(unit=="us") sec_divide=1e-6;\
	else if(unit=="ms") sec_divide=1e-3;\
	else if(unit=="s") sec_divide=1;\
	else if(unit=="min") sec_divide=60;\
	else if(unit=="h") sec_divide=3600;\
	else if(unit=="d") sec_divide=86400;\
	return double(finish-start)/CLOCKS_PER_SEC/sec_divide;
typedef long double LONGEST_FLOAT;
template<typename T>
LONGEST_FLOAT gettime(T func,const char* unit="ms"){  // func's argument must be void
	FUNCTION_CODE(func())
}
template<typename T,typename Taug1>
LONGEST_FLOAT gettime(T func,Taug1 argument1,const char* unit="ms"){ //func's argument is (only one)
	FUNCTION_CODE(func(argument1))
} 
template<typename T,typename Taug1,typename Taug2>
LONGEST_FLOAT gettime(T func,Taug1 argument1,Taug2 argument2,const char* unit="ms"){  //...
	FUNCTION_CODE(func(argument1,argument2))
} 
template<typename T,typename Taug1,typename Taug2,typename Taug3>
LONGEST_FLOAT gettime(T func,Taug1 argument1,Taug2 argument2,Taug3 argument3,const char* unit="ms"){
	FUNCTION_CODE(func(argument1,argument2,argument3));
} 
#endif

因为重复的代码太多了,所以我先把函数体定义成了一个宏。

可以用这个函数测试cout的速度:

#include"E:\C++ h\gettime.h"  // 这是我在计算机里存的路径,用的时候需要根据实际路径替换
#include<iostream>
#include<iomanip>
using namespace std;
int f(int a){
	for(int i=0;i<a;i++) cout<<"1\b";
	return a;
}
int main(){
	long double mintime=1e+30,maxtime=0;
	cout<<"  The 1:\n";
	for(int i=0;;i++){
		long double functime=gettime<int(*)(int)>(f,10000,"ms"); // 也可以不要尖括号和它里面的内容
		bool min_max=0;
		if(functime<mintime) mintime=functime,cout<<functime<<" *min\n",min_max=1;
		if(functime>maxtime) maxtime=functime,cout<<functime<<" *max\n",min_max=1;
		if(!min_max) cout<<functime<<"\n";
		if(i%10==9){
			cout<<"\t\tmin:"<<mintime<<"  max:"<<maxtime<<"\n  The "<<i/10+2<<":\n";
                }
        }
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41461277/article/details/84828652