求余操作与按位操作的效率

需求:奇偶数判断 / 二进制数最后一位是0 or 1问题的判断
正常方法: n % 2 == 0 偶数
按位操作: n & 1 == 0 偶数
在LeetCode第190. Reverse Bits中600个测试用例,求余操作提交多次大部分都用时4ms,而按位与操作则为0ms。
如果只看这个例子,仿佛求余操作的效率不如按位与操作,那么不妨来一次实验验证一下吧。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{
	int n = 0x5fffffff;
	int i;
	clock_t start,end;
	double time;

	start = clock();
	for(i = 0; i < 1000000000; i++)
	{
		if(n % 2 == 1)
			continue;
	}	
	end = clock();
	time = (double)(end - start)/CLOCKS_PER_SEC;
	printf("time1 is %f seconds\n",time);

	start = clock();
	for(i = 0; i < 1000000000; i++)
	{
		if(n & 1 == 1)
			continue;
	}	
	end = clock();
	time = (double)(end - start)/CLOCKS_PER_SEC;
	printf("time2 is %f seconds\n",time);

}

      连续执行程序10次,花费时间如下:

操作\时间(s) 1 2 3 4 5 6 7 8 9 10 average
求余操作 2.69 2.62 3.57 2.63 2.51 2.47 2.83 2.51 2.54 2.48 2.685
按位与操作 2.47 2.38 2.65 2.66 3.29 2.55 2.47 2.68 2.60 2.46 2.621
实验证明位运算确实效率高一些,但总体差距不大。

猜你喜欢

转载自blog.csdn.net/g1269420003/article/details/80455804