在宏定义中使用可变参数实现任意函数计时打印

想实现的效果

我想对任意一个函数可以实现计时打印,打印出:[函数名]:[耗时]。比如:

void function(int a,int b,int c);
void function2(float d);
check_perf(function,a,b,c);
check_perf(function2,d);

有点像切片编程的意思,但是C++实现AOP还是蛮烦的,我暂时只想记个时,不想用牛刀。所以就使用了可变参的宏。主要就是涉及#、##、__VA_ARGS__三个东西。

代码

#include<chrono>
#define check_perf(func, ...)\
	{
      
      \
	auto t1 = chrono::system_clock::now();\
	func(##__VA_ARGS__);\
	auto t2 = chrono::system_clock::now();\
	auto time = chrono::duration_cast<chrono::milliseconds>(t2 - t1).count();\
	printf("[%s] pass time : %d ms\n",#func,time);\
	}
void add(int a,int b,int c){
    
    }
void sub(int a,float b){
    
    }
int main()
{
    
    
	int a,b,c;
	a=b=c=0;
	check_perf(add,a,b,c);
	check_perf(sub,a,b);
}

##的作用:

##是粘贴的作用,把前后两个东西直接粘连起来,比如:

#define XNAME(n) x##n
XNAME(1) = 1;// x1=1

#的作用

#是取字符串的作用,比如:

#define XNAME(n) #n
const char* fuck = XNAME(fuck); // const char* fuck = "fuck";

__VA_ARGS__的作用

__VA_ARGS__是可变参的宏替换,##__VA_ARGS__就可以代表宏定义中的那个省略号,在比如我们常用可能会自定义一个宏打印控制printf的开关:

#define log_printf(...) printf(##__VA_ARGS__)

这么定义无论你输入什么参数到printf都不会出错

猜你喜欢

转载自blog.csdn.net/qq_16952303/article/details/121137944