C++次方函数性能测试结果

avatar
作者
筋斗云
阅读量:0

以下是对C++中次方函数的性能测试结果:

  1. 使用自定义的次方函数:
#include <iostream> #include <chrono>  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<double> 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

  1. 使用标准库中的pow函数:
#include <iostream> #include <cmath> #include <chrono>  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<double> 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函数性能更好,执行时间更短。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!