# How NetworkSampler Measures Live Bandwidth and Performs Speed Tests in vorssaint-utils

> Discover how NetworkSampler in vorssaint-utils measures live bandwidth and performs speed tests by polling macOS network counters and calculating real-time metrics. Learn more!

- Repository: [vorssaint/vorssaint-utils](https://github.com/vorssaint/vorssaint-utils)
- Tags: how-to-guide
- Published: 2026-09-11

---

**NetworkSampler** polls macOS network counters via the `nettop` command, calculates delta bytes over time to derive upload and download speeds, and exposes real-time metrics through Combine publishers while supporting dedicated speed-test sessions through temporary high-frequency sampling.

The `NetworkSampler` class in **vorssaint-utils** provides the backbone for live bandwidth monitoring and on-demand speed testing in macOS applications. By transforming raw byte counters from system interfaces into human-readable transfer rates, this service drives both the menu-bar network indicator and the dedicated network performance tests. Understanding how NetworkSampler measures live bandwidth and performs speed tests reveals a robust architecture built on delta calculations, resilient fallback mechanisms, and reactive data streams.

## Core Architecture and Data Acquisition

Located in [`Sources/Vorssaint/Services/Metrics/NetworkSampler.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Metrics/NetworkSampler.swift), the sampler operates on a timer-based polling mechanism that initializes with a `counterReader` closure. This closure returns a `NetworkCounters` struct containing cumulative bytes received and transmitted. In production environments, the reader wraps `NetworkProcessSupport.currentNetworkCounters()`, which executes the macOS `nettop` utility and parses its CSV output via `NetworkProcessSupport.parseNettopCSV` according to the implementation in [`Sources/Vorssaint/Services/Metrics/NetworkProcessSupport.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Metrics/NetworkProcessSupport.swift).

### Delta Calculation for Live Transfer Rates

On each sampling tick, the service stores the previous `NetworkCounters` instance and timestamp, then computes the difference between sequential readings. The sampler derives **download speed** by dividing `bytesIn` by the delta time (`Δt`), and **upload speed** by dividing `bytesOut` by `Δt`, yielding rates in bytes per second. This calculation logic appears in the sampler’s update loop where counter deltas are converted to instantaneous throughput metrics.

### Resilient Sampling with NetworkCounterFallback

When the `counterReader` returns `nil` or encounters a polling failure, the sampler invokes the `NetworkCounterFallback` mechanism implemented within the same file. This utility substitutes the last known valid counter values, ensuring the UI never displays sudden dropouts to zero during transient system delays or permission issues. The fallback logic specifically checks for missing samples and seamlessly bridges gaps using historical data.

## Publishing Bandwidth Data to the User Interface

`NetworkSampler` exposes `downloadSpeed` and `uploadSpeed` as `@Published` `Double` properties, emitting continuous updates in bytes per second. SwiftUI views such as `NetworkSection` in [`Sources/Vorssaint/UI/MenuPanel/NetworkSection.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/UI/MenuPanel/NetworkSection.swift) subscribe to these publishers, mapping the raw values through `ByteCountFormatter` to generate human-readable strings for the network card and menu-bar indicator.

## Speed Test Implementation and Validation

For on-demand speed tests, `NetworkSampler` initiates a temporary high-frequency sampling session that aggregates bandwidth measurements over a defined duration. During test execution, the sampler collects delta calculations at 1-second intervals and computes average throughput statistics. The test harness in [`Tests/SpeedTestTests.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Tests/SpeedTestTests.swift) validates this behavior, verifying that the sampler correctly accumulates and reports bandwidth metrics after the test period completes. Unit tests in [`Tests/MetricsTests.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Tests/MetricsTests.swift) additionally verify the low-level counter handling and fallback logic under simulated failure conditions.

## Practical Integration Example

The following Swift implementation demonstrates initializing the sampler with system counter integration, subscribing to live bandwidth updates, and executing a one-off speed test:

```swift
import Combine
import SwiftUI

// Initialize with the production nettop-based reader
let sampler = NetworkSampler(counterReader: {
    NetworkProcessSupport.currentNetworkCounters()
})

// Start live monitoring
sampler.start()

// Subscribe to live bandwidth updates for UI display
var cancellables = Set<AnyCancellable>()

sampler.$downloadSpeed
    .map { ByteCountFormatter.string(fromByteCount: Int64($0), countStyle: .binary) }
    .sink { formattedDownload in
        print("Current download: \(formattedDownload)/s")
    }
    .store(in: &cancellables)

sampler.$uploadSpeed
    .map { ByteCountFormatter.string(fromByteCount: Int64($0), countStyle: .binary) }
    .sink { formattedUpload in
        print("Current upload: \(formattedUpload)/s")
    }
    .store(in: &cancellables)

// Execute a 5-second speed test
sampler.performSpeedTest(duration: 5.0) { result in
    print("Speed test completed")
    print("Average download: \(result.download) bytes/s")
    print("Average upload: \(result.upload) bytes/s")
}

```

## Summary

- **NetworkSampler** resides in [`Sources/Vorssaint/Services/Metrics/NetworkSampler.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Metrics/NetworkSampler.swift) and provides the core bandwidth measurement engine for vorssaint-utils.
- The service acquires raw data through a pluggable `counterReader` closure, with production implementations parsing `nettop` CSV output via `NetworkProcessSupport.parseNettopCSV`.
- Live transfer rates are calculated by computing delta bytes divided by delta time between sequential counter readings.
- The `NetworkCounterFallback` mechanism ensures continuous data availability by substituting the last valid sample when polling fails.
- Real-time metrics flow to the UI through `@Published` properties consumed by SwiftUI views like `NetworkSection`.
- Speed tests utilize temporary high-frequency sampling sessions validated by the test suite in [`Tests/SpeedTestTests.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Tests/SpeedTestTests.swift).

## Frequently Asked Questions

### How does NetworkSampler read system network statistics?

The sampler accepts a `counterReader` closure at initialization that returns a `NetworkCounters` struct. In production, this closure invokes `NetworkProcessSupport.currentNetworkCounters()`, which shells out to the macOS `nettop` command and parses the resulting CSV data to extract total bytes received and sent on the primary interface.

### What happens when network counter data is temporarily unavailable?

When a sample read returns `nil` or encounters an error, the sampler activates `NetworkCounterFallback` logic to substitute the previous valid counter values. This prevents the live indicator from displaying zero values during transient polling gaps and maintains smooth visualization in the menu bar.

### How does the speed test mode differ from regular monitoring?

While standard monitoring operates at the default timer interval, speed test mode initiates a temporary high-frequency sampling session that aggregates delta calculations over the test duration. This concentrated measurement window provides accurate average throughput statistics for the specific testing period rather than general system usage.

### Which source files contain the bandwidth calculation implementation?

The primary implementation lives in [`Sources/Vorssaint/Services/Metrics/NetworkSampler.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Metrics/NetworkSampler.swift), with system interface logic in [`Sources/Vorssaint/Services/Metrics/NetworkProcessSupport.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Metrics/NetworkProcessSupport.swift). The UI consumption layer appears in [`Sources/Vorssaint/UI/MenuPanel/NetworkSection.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/UI/MenuPanel/NetworkSection.swift), while [`Tests/SpeedTestTests.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Tests/SpeedTestTests.swift) and [`Tests/MetricsTests.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Tests/MetricsTests.swift) contain validation suites for the calculation and fallback logic.