C++ 求模運算優化

最近刷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;
}

在這裏插入圖片描述
在這裏插入圖片描述
由此可見,還是有微小差距的,但是只有在大量運算的情況下這種寫法纔有一點點用,否則影響代碼可讀性,得不償失。
以上爲本地測試結果,如果作者理解有誤,請指正。

發佈了11 篇原創文章 · 獲贊 3 · 訪問量 3003
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章