以下是對C++中次方函數的性能測試結果:
#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
#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函數性能更好,執行時間更短。