-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance_test.cpp
More file actions
75 lines (59 loc) · 1.81 KB
/
Copy pathperformance_test.cpp
File metadata and controls
75 lines (59 loc) · 1.81 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <chrono>
#include <vector>
#include "include/Complexe.h"
using namespace std;
using namespace chrono;
// 指针版本(简化)
class ComplexePtr {
public:
double* R;
double* I;
ComplexePtr(double r = 0, double i = 0) {
R = new double(r);
I = new double(i);
}
~ComplexePtr() {
delete R;
delete I;
}
ComplexePtr operator+(const ComplexePtr& other) const {
return ComplexePtr(*R + *other.R, *I + *other.I);
}
};
const int N = 100000;
int main() {
cout << "=== 性能对比测试 ===" << endl;
// 测试当前实现
vector<Complexe> vec1;
vec1.reserve(N);
auto start = high_resolution_clock::now();
for (int i = 0; i < N; i++) {
vec1.emplace_back(i, i + 1);
}
// 执行一些运算
Complexe sum(0, 0);
for (const auto& c : vec1) {
sum = sum + c;
}
auto end = high_resolution_clock::now();
auto duration1 = duration_cast<microseconds>(end - start);
cout << "当前实现 (直接存储): " << duration1.count() << " 微秒" << endl;
// 测试指针版本
vector<ComplexePtr> vec2;
vec2.reserve(N);
start = high_resolution_clock::now();
for (int i = 0; i < N; i++) {
vec2.emplace_back(i, i + 1);
}
// 执行运算(这里会有问题,但展示概念)
// ComplexePtr sum2(0, 0);
// for (const auto& c : vec2) {
// sum2 = sum2 + c; // 这里会有内存泄漏!
// }
end = high_resolution_clock::now();
auto duration2 = duration_cast<microseconds>(end - start);
cout << "指针版本: " << duration2.count() << " 微秒" << endl;
cout << "性能比率: " << (double)duration2.count() / duration1.count() << "x 慢" << endl;
return 0;
}