forked from monahc1/ProjetFonc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
73 lines (58 loc) · 1.88 KB
/
Copy pathstack.cpp
File metadata and controls
73 lines (58 loc) · 1.88 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
#include <iostream>
#include <memory>
#include <functional>
#include <stdexcept>
#include <chrono>
#include <algorithm>
#include <memory>
template<typename T>
class Stack {
public:
struct Node {
T value;
std::shared_ptr<const Node> next;
Node(T val, std::shared_ptr<const Node> nxt = nullptr) : value(val), next(nxt) {}
};
std::shared_ptr<const Node> head;
public:
Stack() : head(nullptr) {}
Stack(std::shared_ptr<const Node> nodes) : head(nodes) {}
Stack push(T value) const {
return Stack(std::make_shared<const Node>(value, head));
}
Stack pop() const {
if (!head) throw std::out_of_range("Empty stack");
return Stack(head->next);
}
T top() const {
if (!head) throw std::out_of_range("Empty stack");
return head->value;
}
bool isEmpty() const {
return head == nullptr;
}
};
void benchmarkStack(size_t n) {
Stack<int> stack;
std::vector<int> values(n);
std::generate(values.begin(), values.end(), []() { return std::rand() % 1000000; });
auto start = std::chrono::high_resolution_clock::now();
// Push all elements onto the stack
for (int value : values) {
stack = stack.push(value);
}
size_t memoryUsage = n * (sizeof(int) + sizeof(std::shared_ptr<const typename Stack<int>::Node>));
while (!stack.isEmpty()) {
stack = stack.pop();
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
std::cout << "Time taken to push and pop " << n << " elements: " << duration.count() << " milliseconds\n";
std::cout << "Memory used: " << memoryUsage << " bytes\n";
}
int main() {
benchmarkStack(100000);
benchmarkStack(200000);
benchmarkStack(500000);
return 0;
}