C语言宏统计代码块时间(一段有趣代码)

一段有趣的代码

利用宏统计代码块占用时间,利用了几个的有趣语法,代码如下:

uint64_t get_time_us()
{
	struct timeval t_now;
	gettimeofday(&t_now, NULL);
	uint64_t u64_now = t_now.tv_sec * 1000000L + t_now.tv_usec;
	return u64_now;
}

#define clock_count(x) do{\
	static __thread uint64_t __clk_last = 0;\
	static __thread uint64_t __clk_num;\
	uint64_t u64_stime = get_time_us();\
	if(0 == __clk_last) __clk_last = u64_stime;\
	x;\
	uint64_t u64_etime = get_time_us();\
	__clk_num += (u64_etime - u64_stime);\
	if(1000000 < u64_etime - __clk_last)\
	{\
		printf("#%lu, %s@%dL: %lu===>%lu us!\n", pthread_self(), __FUNCTION__, __LINE__, u64_etime - __clk_last, __clk_num);\
		__clk_last = u64_etime;\
		__clk_num = 0;\
	}\
}while(0)

int main(int argc, char **argv)
{
	for(int i = 0; i < 30000; i++)
	{
		usleep(50);
		
		clock_count(
			usleep(50);
		);
	}
	return 0;
}

上述代码有趣的地方:

  1. 函数调用表达式可以作为带参数宏的实参,跟函数有很大区别了,加深了体会,宏真的是傻傻的展开代码
  2. 代码块内定义变量,作用域不会出该代码块
  3. static修饰局部变量,成为了代码块私有全局变量
  4. __pthread修饰局部变量,宏获得了线程安全性
  5. \符号表示忽略回车,表示仍是一行,未开新行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值