温馨提示×

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

c++
小樊
84
2024-07-25 16:29:16
栏目: 编程语言
C++开发者专用服务器限时活动,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函数性能更好,执行时间更短。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:C++次方函数如何实现

0