C++异常性能分析对比

109 阅读1分钟
#include <iostream>
#include <vector>
#include <chrono>
#include <stdexcept>

// 使用异常处理计算平均值
double calculateAverageWithException(const std::vector<int> &data) {
    if (data.empty()) {
        throw std::runtime_error("Array is empty");
    }

    double sum = 0;
    for (int value: data) {
        sum += value;
    }
    return sum / data.size();
}

// 使用错误码计算平均值
double calculateAverageWithErrorCode(const std::vector<int> &data, bool &error) {
    error = false;
    if (data.empty()) {
        error = true;
        return 0;
    }

    double sum = 0;
    for (int value: data) {
        sum += value;
    }
    return sum / data.size();
}

// 预热函数
void warmup(const std::vector<int> &data) {
    for (int i = 0; i < 10; ++i) {
        try {
            calculateAverageWithException(data);
        } catch (const std::runtime_error &e) {
            // std::cout << "Error: " << e.what() << std::endl;
        }

        bool error;
        calculateAverageWithErrorCode(data, error);
    }
}

// 测试异常处理的性能
double testPerformanceException(const std::vector<int> &data) {
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 100; ++i) {
        try {
            calculateAverageWithException(data);
        } catch (const std::runtime_error &e) {
            // std::cout << "Error: " << e.what() << std::endl;
        }
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end - start;
    return elapsed.count() / 100; // 返回平均时间
}

// 测试错误码的性能
double testPerformanceErrorCode(const std::vector<int> &data) {
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < 100; ++i) {
        bool error;
        calculateAverageWithErrorCode(data, error);
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end - start;
    return elapsed.count() / 100; // 返回平均时间
}

int no_error_perf() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 测试数据

    warmup(data); // 预热

    double avgTimeException = testPerformanceException(data);
    std::cout << "Average Time Taken (Exception): " << avgTimeException << " ms\n";

    double avgTimeErrorCode = testPerformanceErrorCode(data);
    std::cout << "Average Time Taken (Error Code): " << avgTimeErrorCode << " ms\n";

    return 0;
}

int error_perf() {
    std::vector<int> data = {}; // 测试数据

    warmup(data); // 预热

    double avgTimeException = testPerformanceException(data);
    std::cout << "Average Time Taken (Exception): " << avgTimeException << " ms\n";

    double avgTimeErrorCode = testPerformanceErrorCode(data);
    std::cout << "Average Time Taken (Error Code): " << avgTimeErrorCode << " ms\n";

    return 0;
}


int main() {
    error_perf();

    return 0;
}