确定求幂技术的效率
通常,将数字与其本身相乘而不是使用专用于求幂的函数,会更有效,就像 pow() 一样。但是,此规则可能有例外,特别是对于某些指数。
考虑以下代码来测试 xx... 和 pow(x,i) 对于不同的性能指数 'i':
#include <cstdlib> #include <cmath> #include <boost/date_time/posix_time/posix_time.hpp> inline boost::posix_time::ptime now() { return boost::posix_time::microsec_clock::local_time(); } #define TEST(num, expression) \ double test##num(double b, long loops) \ { \ double x = 0.0; \ boost::posix_time::ptime startTime = now(); \ for (long i=0; i<loops; ++i) \ { \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ x += expression; \ } \ boost::posix_time::time_duration elapsed = now() - startTime; \ std::cout << elapsed << " "; \ return x; \ } // Test cases for exponentiation using x*x... TEST(1, b) TEST(2, b*b) TEST(3, b*b*b) TEST(4, b*b*b*b) TEST(5, b*b*b*b*b) // Test cases for exponentiation using pow() template <int exponent> double testpow(double base, long loops) { double x = 0.0; boost::posix_time::ptime startTime = now(); for (long i = 0; i < loops; ++i) { x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); x += std::pow(base, exponent); } boost::posix_time::time_duration elapsed = now() - startTime; std::cout << elapsed << " "; return x; } int main() { long loops = 100000000l; double x = 0.0; std::cout << "1 "; x += testpow<1>(rand(), loops); x += test1(rand(), loops); std::cout << "\n2 "; x += testpow<2>(rand(), loops); x += test2(rand(), loops); std::cout << "\n3 "; x += testpow<3>(rand(), loops); x += test3(rand(), loops); std::cout << "\n4 "; x += testpow<4>(rand(), loops); x += test4(rand(), loops); std::cout << "\n5 "; x += testpow<5>(rand(), loops); x += test5(rand(), loops); std::cout << "\n" << x << "\n"; }
结果
测试结果测量每种求幂方法所需的时间,证明 xx...确实更快。
但是,也有一些例外
关于 pow(x, 3),结果可能会因编译器和优化而异标志,特别是在使用“double”等浮点变量时。
在某些情况下,xxx*... 并不总是比 pow(x, 3) 更快,因为在一些报告的基准中观察到。这是由于现代编译器采用的优化技术。
结论
虽然 xx... 对于小指数值(例如1、2 或 3,在确定最有效的代码方法时,必须考虑具体的实现细节和编译器优化。
以上是使用'x*x...”而不是'pow(x, i)”进行求幂总是更快吗?的详细内容。更多信息请关注PHP中文网其他相关文章!