#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) {
}
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) {
}
}
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;
}