example3_memory_usage_benchmarking.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
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <chrono>
#include <memory>
#include <cstdio>

#ifdef __unix__
#include <unistd.h>
#include <sys/resource.h>
#elif defined(_WIN32)
#include <windows.h>
#include <psapi.h>
#endif

// A simple class to allocate memory
class MemoryUser {
    std::unique_ptr<char[]> buffer;
public:
    MemoryUser(size_t size) : buffer(new char[size]) {}
};

// Function to measure memory usage
size_t getCurrentRSS() {
#ifdef __unix__
    struct rusage rusage;
    if (getrusage(RUSAGE_SELF, &rusage) != 0) {
        return 0;
    }
    return (size_t)(rusage.ru_maxrss * 1024L);
#elif defined(_WIN32)
    PROCESS_MEMORY_COUNTERS_EX pmc;
    if (GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc))) {
        return pmc.WorkingSetSize;
    }
    return 0;
#else
    // For other operating systems, you might need to implement a different method
    return 0;
#endif
}

int main() {
    const int NUM_OBJECTS = 1000000;
    const int OBJECT_SIZE = 1000;

    size_t initialMemory = getCurrentRSS();

    auto start = std::chrono::high_resolution_clock::now();

    std::vector<MemoryUser> objects;
    objects.reserve(NUM_OBJECTS);

    for (int i = 0; i < NUM_OBJECTS; ++i) {
        objects.emplace_back(OBJECT_SIZE);
    }

    auto end = std::chrono::high_resolution_clock::now();
    size_t finalMemory = getCurrentRSS();

    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);

    std::cout << "Time taken: " << duration.count() << " milliseconds" << std::endl;
    std::cout << "Memory used: " << (finalMemory - initialMemory) / (1024 * 1024) << " MB" << std::endl;

    return 0;
}
Back to benchmarking