我正在编写查找质数的代码,期间我对C ++中的%运算符在低层次上如何工作产生了好奇。
首先,我编写了一些代码来比较'%'运算符和 '>>'运算符的每个所花费的时间。
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
bool remainder1(int x);
bool remainder2(int y);
void timeCompare(bool(*f)(int), bool(*g)(int));
// I want to check which one is faster, x % 2 Vs. (x >> 1) & 1
int main()
{
srand(time(NULL));
for (int i = 0; i < 10; i++) {
timeCompare(remainder1, remainder2);
}
return 0;
}
// % 2 operation
bool remainder1(int x) {
if (x % 128) return true;
else return false;
}
bool remainder2(int x) {
if ((x >> 7) & 1) return true;
else return false;
}
void timeCompare(bool(*f)(int), bool(*g)(int)) {
srand(time(NULL));
auto start = chrono::steady_clock::now();
for (int i = 0; i < 10000000; i++) {
int x = rand();
f(x);
}
auto end = chrono::steady_clock::now();
cout << "Elapsed time in nanoseconds : "
<< chrono::duration_cast<chrono::nanoseconds>(end - start).count()
<< " ns";
auto start2 = chrono::steady_clock::now();
for (int i = 0; i < 10000000; i++) {
int x = rand();
g(x);
}
auto end2 = chrono::steady_clock::now();
cout << " Vs. "
<< chrono::duration_cast<chrono::nanoseconds>(end2 - start2).count()
<< " ns" << endl;
}
输出结果如下:
Elapsed time in nanoseconds : 166158000 ns Vs. 218736000 ns
Elapsed time in nanoseconds : 151776000 ns Vs. 214823000 ns
Elapsed time in nanoseconds : 162193000 ns Vs. 217248000 ns
Elapsed time in nanoseconds : 151338000 ns Vs. 211793000 ns
Elapsed time in nanoseconds : 150346000 ns Vs. 211295000 ns
Elapsed time in nanoseconds : 155799000 ns Vs. 215265000 ns
Elapsed time in nanoseconds : 148801000 ns Vs. 212839000 ns
Elapsed time in nanoseconds : 149813000 ns Vs. 226175000 ns
Elapsed time in nanoseconds : 152324000 ns Vs. 213338000 ns
Elapsed time in nanoseconds : 149353000 ns Vs. 216809000 ns
看起来位移操作在查找余数时比较慢。我猜想原因是位移版本需要比“%”版本多一次比较... 我的猜测正确吗?
我真的很想知道“%”在低层级是如何工作的!
return x & 127;
这样的形式,所以它比位移版本少了一些操作。另外请注意,你的第二个函数实际上并没有和第一个函数做相同的事情(如果你想要找到除以2的余数,那么就不需要位移,这样做有点奇怪)。 - Qubitif (...) return true else return false
而不是return ...
。 - Caleth