Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 10 additions & 24 deletions include/rigtorp/SPSCQueue.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ SOFTWARE.

#pragma once

#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstddef>
#include <memory> // std::allocator
#include <new> // std::hardware_destructive_interference_size
#include <stdexcept>
#include <type_traits> // std::enable_if, std::is_*_constructible

#ifdef __has_cpp_attribute
Expand Down Expand Up @@ -58,15 +58,8 @@ template <typename T, typename Allocator = std::allocator<T>> class SPSCQueue {
explicit SPSCQueue(const size_t capacity,
const Allocator &allocator = Allocator())
: capacity_(capacity), allocator_(allocator) {
// The queue needs at least one element
if (capacity_ < 1) {
capacity_ = 1;
}
capacity_++; // Needs one slack element
// Prevent overflowing size_t
if (capacity_ > SIZE_MAX - 2 * kPadding) {
capacity_ = SIZE_MAX - 2 * kPadding;
}
// The queue needs at least one element plus one slack
capacity_ = std::min(std::max(capacity_ + 1, 2ul), SIZE_MAX - 2 * kPadding);

#if defined(__cpp_if_constexpr) && defined(__cpp_lib_void_t)
if constexpr (has_allocate_at_least<Allocator>::value) {
Expand Down Expand Up @@ -107,10 +100,7 @@ template <typename T, typename Allocator = std::allocator<T>> class SPSCQueue {
static_assert(std::is_constructible<T, Args &&...>::value,
"T must be constructible with Args&&...");
auto const writeIdx = writeIdx_.load(std::memory_order_relaxed);
auto nextWriteIdx = writeIdx + 1;
if (nextWriteIdx == capacity_) {
nextWriteIdx = 0;
}
auto nextWriteIdx = (writeIdx + 1) % capacity_;
while (nextWriteIdx == readIdxCache_) {
readIdxCache_ = readIdx_.load(std::memory_order_acquire);
}
Expand All @@ -124,10 +114,7 @@ template <typename T, typename Allocator = std::allocator<T>> class SPSCQueue {
static_assert(std::is_constructible<T, Args &&...>::value,
"T must be constructible with Args&&...");
auto const writeIdx = writeIdx_.load(std::memory_order_relaxed);
auto nextWriteIdx = writeIdx + 1;
if (nextWriteIdx == capacity_) {
nextWriteIdx = 0;
}
auto nextWriteIdx = (writeIdx + 1) % capacity_;
if (nextWriteIdx == readIdxCache_) {
readIdxCache_ = readIdx_.load(std::memory_order_acquire);
if (nextWriteIdx == readIdxCache_) {
Expand Down Expand Up @@ -180,13 +167,12 @@ template <typename T, typename Allocator = std::allocator<T>> class SPSCQueue {
static_assert(std::is_nothrow_destructible<T>::value,
"T must be nothrow destructible");
auto const readIdx = readIdx_.load(std::memory_order_relaxed);
assert(writeIdx_.load(std::memory_order_acquire) != readIdx &&
"Can only call pop() after front() has returned a non-nullptr");
slots_[readIdx + kPadding].~T();
auto nextReadIdx = readIdx + 1;
if (nextReadIdx == capacity_) {
nextReadIdx = 0;
if (readIdx == writeIdxCache_) {
writeIdxCache_ = writeIdx_.load(std::memory_order_acquire);
Comment on lines +170 to +171

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This optimization leads to 66% more ops/ms

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I benchmarked this in optimized Release builds (-DNDEBUG) and could not reproduce a throughput improvement on this machine.

The comparison uses the original PR parent, 1053918dbd251fbff69b24ef27fa5d51c29ec2af, with four variants:

  1. Original: unmodified parent revision.
  2. Cached assertion only: replace writeIdx_.load(std::memory_order_acquire) in the pop() assertion with writeIdxCache_; no other changes.
  3. Conditional cache refresh: variant 2 plus the if (readIdx == writeIdxCache_) refresh highlighted in this thread; retain the original constructor and increment/compare wraparound.
  4. Full PR: exact 552d2eb8453468474e84d304ceffe8c756a3d84d, including the constructor changes and % capacity_ wraparound.

Results are medians of 16 measured rounds, with variant order randomized within each round after warmup:

Version Large-capacity throughput (Mops/s, higher is better) Bounded throughput (Mops/s, higher is better) Round-trip latency (ns, lower is better)
Original 811.698 161.358 152.499
Cached assertion only 813.806 157.354 152.878
Conditional cache refresh 759.020 153.123 153.340
Full PR 378.436 137.385 153.729

Test details:

  • AMD Ryzen 7 8745HS, Linux x86-64. Consumer pinned to CPU 2 and producer to CPU 3, on separate physical cores on the same socket.
  • GCC 16.2.1; -std=c++17 -O3 -march=native -DNDEBUG -pthread. Assertions are disabled in every result above.
  • A standalone harness testing only rigtorp::SPSCQueue<uint64_t>, rather than the repository's multi-queue benchmark executable. Each receive waits for a non-null front(), reads the value, then calls pop(). The receive helper is forced inline so front() and pop() stay together in the consumer loop.
  • Each throughput measurement transfers 30 million items. The large-capacity queue holds 262,144 items; the bounded queue holds 8,192. Both start with 4,096 items prefilled. One operation means one item transferred from producer to consumer. Queue occupancy can change during the run; a permanent backlog is not enforced.
  • RTT measures 200,000 ping-pong exchanges through two capacity-16 queues. The producer sends one item and waits for its echo before sending the next.
  • Synchronized start after both threads are pinned and ready. Thread startup and prefill are outside the timed interval; thread join is included. Received-value checksums are accumulated during the transfer and verified outside the timed interval.
  • Each process performs a short throughput warmup; each executable also receives a complete discarded run before measured rounds.

The cached-assertion-only and original Release executables have byte-identical .text sections, as expected when the assertion is compiled out. Their measurement differences should therefore be treated as run-to-run variation.

The conditional refresh measured about 6.5% lower large-capacity throughput than the original here. The large-capacity throughput interquartile ranges were 776.5–837.8 Mops/s for the original and 734.5–771.2 Mops/s for the refresh variant. The refresh changes generated code despite being redundant for a valid successful-front()/pop() sequence.

The full PR measured about 53.4% lower large-capacity throughput. Disassembly shows integer divide instructions in that variant, while the three variants retaining the original wraparound have none; this is consistent with a cost from the modulo changes, although this comparison does not isolate modulo from every other full-PR change.

These are local measurements with frequency boost enabled, without fixed-frequency or OS CPU isolation. They do not establish a universal percentage, but they provide no evidence of a Release performance improvement from the proposed refresh on this machine.

}
assert(writeIdxCache_ != readIdx && "Can only call pop() after front() has returned a non-nullptr");
slots_[readIdx + kPadding].~T();
auto nextReadIdx = (readIdx + 1) % capacity_;
readIdx_.store(nextReadIdx, std::memory_order_release);
}

Expand Down