我是靠谱客的博主 美丽烧鹅,最近开发中收集的这篇文章主要介绍求偶数之取模运算(%)与位运算(&)速度之比较,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

先开门见山,直接给结论:

结论一:【位运算】比【取模运算】要快,至于快多少,详见以下程序注释

结论二:内置原始数组int[ ]在存储速度方面快至少一个数量级

代码运行平台:windows7,x86(32)2G内存,双核,CPU频率:3GHz,IDE:VS2010

说明:测试数字带【*】的,是此次测试的例外情况;但综合看:结论依然是——位运算】比【取模运算】要快

个人姑且认为原因是:a % n = a - n * floor( a / n )。

/*
* 测试在求偶数时取模运算和位运算的速度
* 20131013 13:13
* 位运算 快于 取模运算,分别用vector和内置数组存储结果
 */
#include <iostream>
#include <Windows.h>
// #include <vector>
using namespace std;
int main()
{
LARGE_INTEGER liStart = {};
LARGE_INTEGER liEnd = {};
QueryPerformanceFrequency(&liStart);
LONGLONG freq = liStart.QuadPart; // 2922451
int len = 200000;
int conlen = len / 2;
//
vector<int> container1(conlen, -1);
//
vector<int> container2(conlen, -2);
int *container1 = new int[conlen]();
int *container2 = new int[conlen]();
int j = 0;
QueryPerformanceCounter(&liStart);
for (int i = 0; i != len; ++i)
{
if (i % 2 == 0)
{
container1[j++] = i;
}
}
QueryPerformanceCounter(&liEnd);
cout << "modulo: time elapsed " << (liEnd.QuadPart - liStart.QuadPart) * 1000.0 / freq << " ms" << endl;
j = 0;
QueryPerformanceCounter(&liStart);
for (int i = 0; i != len; ++i)
{
if ((i & 1) == 0)
{
container2[j++] = i;
}
}
QueryPerformanceCounter(&liEnd);
cout << "bitand: time elapsed " << (liEnd.QuadPart - liStart.QuadPart) * 1000.0 / freq << " ms" << endl;
delete[] container1;
delete[] container2;
/*
vector<int>
int[]
10000
1st
modulo: time elapsed 0.787011 ms	modulo: time elapsed 0.0376396 ms
bitand: time elapsed 0.771955 ms	bitand: time elapsed 0.0362709 ms
2nd
modulo: time elapsed 0.747318 ms	modulo: time elapsed 0.0376396 ms
bitand: time elapsed 0.740817 ms	bitand: time elapsed 0.0417458 ms *
3rd
modulo: time elapsed 0.788379 ms	modulo: time elapsed 0.038324 ms
bitand: time elapsed 0.77127 ms
bitand: time elapsed 0.0427723 ms *
50000
1st
modulo: time elapsed 4.8887 ms
modulo: time elapsed 0.19949 ms
bitand: time elapsed 4.03942 ms
bitand: time elapsed 0.212151 ms *
2nd
modulo: time elapsed 5.09914 ms
modulo: time elapsed 0.197779 ms
bitand: time elapsed 4.18861 ms
bitand: time elapsed 0.187172 ms
3rd
modulo: time elapsed 4.32582 ms
modulo: time elapsed 0.198464 ms
bitand: time elapsed 4.42368 ms
bitand: time elapsed 0.190593 ms
100000
1st
modulo: time elapsed 0.319937 ms
bitand: time elapsed 0.304881 ms
2nd
modulo: time elapsed 0.384951 ms
bitand: time elapsed 0.377423 ms
3rd
modulo: time elapsed 0.385293 ms
bitand: time elapsed 0.389741 ms *
200000
1st
modulo: time elapsed 0.818149 ms
bitand: time elapsed 0.732604 ms
2nd
modulo: time elapsed 0.79796 ms
bitand: time elapsed 0.765111 ms
3rd
modulo: time elapsed 0.818491 ms
bitand: time elapsed 0.735342 ms
*/
return 0;
}


最后

以上就是美丽烧鹅为你收集整理的求偶数之取模运算(%)与位运算(&)速度之比较的全部内容,希望文章能够帮你解决求偶数之取模运算(%)与位运算(&)速度之比较所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部