相关代码及说明请见下文:
int64_t mulFunc(int64_t a)
{return (int64_t)(a * 0.01);
}int64_t divFunc(int64_t a)
{// 注意,除数必须是整型, 例如你不能把100改为100.0。如果你改了,计算速度将大幅下降(因为这样一来将计算过程变为浮点运算)return a / 100;
}int64_t mulFunc(double a)
{return (int64_t)(a * 0.01);
}int64_t divFunc(double a)
{return a / 100;
}int64_t testMathCalc()
{// thanks: https://www.zhihu.com/question/458395216auto tot = 10000 * 10000;auto start_sys_time = std::chrono::system_clock::now();int64_t value = 0;for (auto i = 0; i < tot; ++i){value = mulFunc(i + 5 + value);}auto current_sys_time = std::chrono::system_clock::now();auto elapsedSysTime = current_sys_time - start_sys_time;auto lossTime = std::chrono::duration_cast<std::chrono::microseconds>(elapsedSysTime).count();std::cout << "mulFunc lossTime: " << lossTime << " us." << std::endl;start_sys_time = std::chrono::system_clock::now();for (auto i = 0; i < tot; ++i){value = divFunc(i + 5 + value);}current_sys_time = std::chrono::system_clock::now();elapsedSysTime = current_sys_time - start_sys_time;lossTime = std::chrono::duration_cast<std::chrono::microseconds>(elapsedSysTime).count();std::cout << "divFunc lossTime: " << lossTime << " us." << std::endl;auto value1 = 0;double doubleValue = 10.1;for (auto i = 0; i < tot; ++i){value1 = mulFunc(i + doubleValue + value1);}current_sys_time = std::chrono::system_clock::now();elapsedSysTime = current_sys_time - start_sys_time;lossTime = std::chrono::duration_cast<std::chrono::microseconds>(elapsedSysTime).count();std::cout << "double mulFunc lossTime: " << lossTime << " us." << std::endl;start_sys_time = std::chrono::system_clock::now();doubleValue = 20.2;for (auto i = 0; i < tot; ++i){value1 = divFunc(i + doubleValue + value1);}current_sys_time = std::chrono::system_clock::now();elapsedSysTime = current_sys_time - start_sys_time;lossTime = std::chrono::duration_cast<std::chrono::microseconds>(elapsedSysTime).count();std::cout << "double divFunc lossTime: " << lossTime << " us." << std::endl;return value + value1;/*结论: 如果是整型除以整型,则这里的测试除法速度快,实际反应出来的原则是:1. 整型乘除法的计算速度都比浮点乘除法计算速度快(计算速度可看作时钟周期数量)2. 浮点乘法速度比浮点除法速度快*/}
打印结果输出:
(整数乘以0.01) mulFunc lossTime: 314071 us.
(整数除以100) divFunc lossTime: 176478 us.
(浮点数乘法) double mulFunc lossTime: 508600 us.
(浮点数除法) double divFunc lossTime: 527787 us.