-
Notifications
You must be signed in to change notification settings - Fork 0
/
cost_compare.cpp
53 lines (47 loc) · 1.29 KB
/
cost_compare.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <chrono>
#include <cstring>
#include <iostream>
void allocateWithTryCatch()
{
try
{
char *data = new char[100];
strcpy(data, "Test");
delete[] data;
}
catch (const std::bad_alloc &e)
{
std::cerr << "Allocation failed: " << e.what() << std::endl;
}
}
void allocateWithoutTryCatch()
{
char *data = new char[100];
strcpy(data, "Test");
delete[] data;
}
int main()
{
const int iterations = 1000000;
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
allocateWithoutTryCatch();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration< double, std::milli > durationWithoutTryCatch =
end - start;
std::cout << "Time taken without try-catch: "
<< durationWithoutTryCatch.count() << " ms" << std::endl;
start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < iterations; ++i)
{
allocateWithTryCatch();
}
end = std::chrono::high_resolution_clock::now();
std::chrono::duration< double, std::milli > durationWithTryCatch =
end - start;
std::cout << "Time taken with try-catch: " << durationWithTryCatch.count()
<< " ms" << std::endl;
return 0;
}