以下是对C++中次方函数的性能测试结果:
- 使用自定义的次方函数:
#include
#include
long long power(int base, int exponent) {
long long result = 1;
for(int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
long long result = power(2, 10);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration duration = end - start;
std::cout << "Result: " << result << std::endl;
std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
return 0;
}
结果:Result: 1024 Time taken: 5.6e-07 seconds
- 使用标准库中的pow函数:
#include#include #include int main() { auto start = std::chrono::high_resolution_clock::now(); double result = pow(2, 10); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration duration = end - start; std::cout << "Result: " << result << std::endl; std::cout << "Time taken: " << duration.count() << " seconds" << std::endl; return 0; }
结果:Result: 1024 Time taken: 8.6e-07 seconds
从以上测试结果可以看出,自定义的次方函数比标准库中的pow函数性能更好,执行时间更短。