溫馨提示×

C++次方函數(shù)性能測試結果

c++
小樊
82
2024-07-25 16:29:16
欄目: 編程語言

以下是對C++中次方函數(shù)的性能測試結果:

  1. 使用自定義的次方函數(shù):
#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函數(shù):
#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

從以上測試結果可以看出,自定義的次方函數(shù)比標準庫中的pow函數(shù)性能更好,執(zhí)行時間更短。

0