C++ 求模运算优化

mac2026-06-15  13

最近刷leetcode,总不太敢用%这个运算符,觉得会耗费效率,于是经常写成下面这样

a - a / b * b;

那么事实上这种写法是否比a%b要快呢,我后来验证了一下

#include<ctime> #include<iostream> using namespace std; void test1(int a,int b,int c) { while (c--) a% b; } void test2(int a, int b, int c) { while (c--) a - a / b * b; } int main() { int a = 95790213; int b = 1234; int c = 300000000; cout << "运算次数:" << c << endl; clock_t startTime, endTime; startTime = clock();//计时开始 test1(a, b, c); endTime = clock();//计时结束 cout << "x%b: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; startTime = clock();//计时开始 test2(a, b, c); endTime = clock();//计时结束 cout << "x-x/b*b: " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl; }

由此可见,还是有微小差距的,但是只有在大量运算的情况下这种写法才有一点点用,否则影响代码可读性,得不偿失。 以上为本地测试结果,如果作者理解有误,请指正。

最新回复(0)