- 반면나눗셈은 훨씬 복잡한 연산이며, 일반적으로더 많은 사이클을 소모합니다 (보통 수십 사이클).
(2) 최적화 관점:
- 컴파일러도 나눗셈을 줄이기 위해 곱셈으로 바꾸려는 최적화를 시도할 수 있습니다. 예: x / 8 → x >> 3 또는 x * 0.125 (정수/부동소수점에 따라 다름)
#include <iostream>
#include <chrono>
int main() {
const int N = 1e8;
volatile int result = 0;
auto start_mul = std::chrono::high_resolution_clock::now();
for (int i = 1; i < N; ++i) result = i * 2;
auto end_mul = std::chrono::high_resolution_clock::now();
auto start_div = std::chrono::high_resolution_clock::now();
for (int i = 1; i < N; ++i) result = i / 2;
auto end_div = std::chrono::high_resolution_clock::now();
std::cout << "곱셈 시간: "
<< std::chrono::duration<double>(end_mul - start_mul).count() << "초\n";
std::cout << "나눗셈 시간: "
<< std::chrono::duration<double>(end_div - start_div).count() << "초\n";
return 0;
}