Skip to the content.

< Previous: Advanced Usage | 🏠 Home | Next: Architecture & Examples >


Performance Metrics

Both UdpListener and UdpSender maintain atomic counters for tracking network throughput and active peers. This allows you to monitor the performance of your application in real-time without introducing significant overhead.

Fetching Stats

You can fetch the current metrics by calling GetStats(), which returns a structure containing cumulative totals.

For UdpListener:

cppudpnet::ListenerStats stats = server.GetStats();
std::cout << "Packets Received: " << stats.packets_received << "\n"
          << "Bytes Received: " << stats.bytes_received << "\n"
          << "Packets Sent: " << stats.packets_sent << "\n"
          << "Bytes Sent: " << stats.bytes_sent << "\n"
          << "Active Peers: " << stats.active_peers << "\n"
          << "Total Historical Peers: " << stats.total_peers << std::endl;

For UdpSender:

cppudpnet::SenderStats stats = client.GetStats();
std::cout << "Packets Sent: " << stats.packets_sent << "\n"
          << "Bytes Sent: " << stats.bytes_sent << std::endl;

To calculate real-time throughput (e.g., Mbps or packets/sec), you can sample GetStats() at regular intervals (e.g., every second) and calculate the delta between the current and previous sample.

Because the counters are atomic, calling GetStats() is safe from any thread and does not block the background worker pool or the event loop.

Sliding-Window Throughput Tracking

cpp-udpnet includes a built-in ThroughputTracker template helper class to measure sliding-window send and receive throughput asynchronously:

#include "cppudpnet.hpp"

// Create a tracker for a UdpSender or UdpListener (polls stats in the background)
cppudpnet::ThroughputTracker<cppudpnet::UdpSender> tracker(client);

// Query real-time send/recv throughput (bytes/second) computed over a 1-second sliding window
double send_speed = tracker.GetSendThroughputBytesPerSec();
double recv_speed = tracker.GetRecvThroughputBytesPerSec();

Because it uses low-frequency background polling of atomic stats rather than per-packet event notifications, ThroughputTracker has virtually zero performance overhead on the hot send and receive paths.


< Previous: Advanced Usage 🏠 Home Next: Architecture & Examples >