-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector_vs_string.cpp
More file actions
51 lines (41 loc) · 1.43 KB
/
Copy pathvector_vs_string.cpp
File metadata and controls
51 lines (41 loc) · 1.43 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
/* g++ -std=c++17 -O2 -pthread vector_vs_string.cpp -o vector_vs_string
./vector_vs_string
*/
#include <chrono>
#include <iostream>
#include <string>
#include <vector>
std::size_t vector_measure(const int &num_elements) {
std::vector<char> vec;
vec.reserve(num_elements);
for (int i = 0; i < num_elements; ++i) {
vec.push_back('a');
}
return vec.size();
}
std::size_t string_measure(const int &num_elements) {
std::string str;
str.reserve(num_elements);
for (int i = 0; i < num_elements; ++i) {
str += 'a';
}
return str.size();
}
int main() {
const int num_elements = 1000000;
// Measure time taken to create a vector of integers
auto start = std::chrono::high_resolution_clock::now();
const std::size_t vec_size = vector_measure(num_elements);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> vec_duration = end - start;
std::cout << "Time taken to create vector: " << vec_duration.count()
<< " seconds (size=" << vec_size << ")" << std::endl;
// Measure time taken to create a string
start = std::chrono::high_resolution_clock::now();
const std::size_t str_size = string_measure(num_elements);
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> str_duration = end - start;
std::cout << "Time taken to create string: " << str_duration.count()
<< " seconds (size=" << str_size << ")" << std::endl;
return 0;
}