-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLatencyTest.cpp
More file actions
93 lines (75 loc) · 2.57 KB
/
LatencyTest.cpp
File metadata and controls
93 lines (75 loc) · 2.57 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#ifdef __linux__
#include <pthread.h>
#endif
#include "messagebroker.hpp"
#include <iostream>
#include <thread>
#include <vector>
#include <numeric>
#include <algorithm>
#include <string>
void pinThreadToCore(std::thread& t, int core_id) {
#ifdef __linux__
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
int rc = pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
std::cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
}
#endif
}
const int NUM_MESSAGES = 5000;
const int64_t TOPIC = 1;
const int64_t CONSUMER_ID = 42;
int main() {
std::cout<<"start"<<std::endl;
MessageBroker broker;
broker.subscribe(TOPIC, CONSUMER_ID);
std::cout<<"debug"<<std::endl;
std::vector<uint64_t> latencies;
latencies.reserve(NUM_MESSAGES);
std::cout<<"debug"<<std::endl;
std::thread producer([&]() {
for (int i = 0; i < NUM_MESSAGES; ++i) {
broker.publish(1, TOPIC, "msg_");
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
});
std::cout<<"debug"<<std::endl;
std::thread consumer([&]() {
int received = 0;
while (received < NUM_MESSAGES) {
Message msg;
if (broker.consume(TOPIC, CONSUMER_ID, msg)) {
uint64_t recv_time = getCurrentTimestamp();
uint64_t latency = recv_time - msg.timestamp;
latencies.push_back(latency);
++received;
} else {
// std::this_thread::yield();
continue;
}
}
});
pinThreadToCore(producer, 1);
pinThreadToCore(consumer, 2);
producer.join();
consumer.join();
std::cout<<"debug"<<std::endl;
std::sort(latencies.begin(), latencies.end());
auto percentile = [&](double p) {
return latencies[static_cast<size_t>(p * (latencies.size() - 1))];
};
long long sum = std::accumulate(latencies.begin(), latencies.end(), 0LL);
std::cout << "\nLatency Benchmark Results (ns):\n";
std::cout << "---------------------------------\n";
std::cout << "Total messages: " << NUM_MESSAGES << "\n";
std::cout << "Min latency: " << latencies.front() << "\n";
std::cout << "Max latency: " << latencies.back() << "\n";
std::cout << "Median: " << percentile(0.5) << "\n";
std::cout << "P95: " << percentile(0.95) << "\n";
std::cout << "P99: " << percentile(0.99) << "\n";
std::cout << "Avg: " << sum / latencies.size() << "\n";
return 0;
}