alamb commented on code in PR #27932:
URL: https://github.com/apache/datafusion/pull/27932#discussion_r4763429583
##########
benchmarks/src/util/reset.rs:
##########
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Returns memory to the OS between iterations, so that the speed of an
+//! iteration does not depend on what ran before it.
+//!
+//! mimalloc can collect only the heap of the calling thread, so
[`reset_memory`]
+//! runs a collection on every thread of the Tokio runtime:
+//!
+//! ```text
+//! each thread: arrive ── collect ── arrive ── collect ── arrive
+//! │ │
+//! │ └ frees memory that another thread
+//! │ owned and released in round one
+//! └ holds the thread, so no thread runs two of the tasks
+//! ```
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::Duration;
+
+use datafusion_common::instant::Instant;
+use tokio::runtime::{Builder, Handle, Runtime};
+
+/// Longest wait for a busy thread. An idle runtime needs milliseconds.
+const TIMEOUT: Duration = Duration::from_secs(2);
+
+/// How often the main thread wakes workers while it waits.
+const NUDGE_INTERVAL: Duration = Duration::from_millis(1);
+
+/// Worker and blocking threads of the runtime that [`build_runtime`] returns.
+static THREADS: AtomicUsize = AtomicUsize::new(0);
+
+/// Builds the multi-threaded runtime that `--reset-memory` needs.
+pub fn build_runtime() -> std::io::Result<Runtime> {
+ Builder::new_multi_thread()
+ .enable_all()
+ .on_thread_start(|| {
+ THREADS.fetch_add(1, Ordering::SeqCst);
+ })
+ .on_thread_stop(|| {
+ THREADS.fetch_sub(1, Ordering::SeqCst);
+ })
+ .build()
+}
+
+/// A barrier that stops waiting at a deadline.
+struct Gate {
+ expected: usize,
+ deadline: Instant,
+ state: Mutex<GateState>,
+ changed: Condvar,
+}
+
+impl Gate {
+ fn new(expected: usize, deadline: Instant) -> Self {
+ Self {
+ expected,
+ deadline,
+ state: Mutex::new(GateState::default()),
+ changed: Condvar::new(),
+ }
+ }
+
+ /// Returns whether all threads arrived before the deadline.
+ ///
+ /// A thread that the timeout releases can run the task of the busy thread.
+ /// That late arrival must not complete the count, so a timeout closes the
+ /// gate for all threads.
+ ///
+ /// A worker takes tasks in batches. It can block here with the task of a
+ /// parked worker in its local queue, and nothing wakes that worker. The
+ /// main thread passes `nudge` to spawn empty tasks, which wake workers
until
+ /// one of them steals the task.
+ fn arrive(&self, nudge: Option<&Handle>) -> bool {
+ let mut state = self.state.lock().unwrap();
+ state.arrived += 1;
+ if state.arrived == self.expected && !state.closed {
+ self.changed.notify_all();
+ return true;
+ }
+ while !state.closed && state.arrived < self.expected {
+ let now = Instant::now();
+ if now >= self.deadline {
+ state.closed = true;
+ self.changed.notify_all();
+ break;
+ }
+ let mut wait = self.deadline - now;
+ if let Some(handle) = nudge {
+ handle.spawn(async {});
+ wait = wait.min(NUDGE_INTERVAL);
+ }
+ (state, _) = self.changed.wait_timeout(state, wait).unwrap();
+ }
+ !state.closed
+ }
+}
+
+#[derive(Default)]
+struct GateState {
+ arrived: usize,
+ closed: bool,
+}
+
+fn on_every_thread(
+ handle: &Handle,
+ workers: usize,
+ blocking: usize,
+ timeout: Duration,
+ action: fn(),
+) -> bool {
+ let deadline = Instant::now() + timeout;
+ let expected = workers + blocking + 1;
+ let gates: Arc<[Gate; 3]> =
+ Arc::new(std::array::from_fn(|_| Gate::new(expected, deadline)));
+ let run = move |gates: &[Gate; 3], nudge: Option<&Handle>| {
+ let mut all = gates[0].arrive(nudge);
+ for gate in &gates[1..] {
+ action();
+ all &= gate.arrive(nudge);
+ }
+ all
+ };
+ for _ in 0..workers {
+ let gates = Arc::clone(&gates);
+ handle.spawn(async move { run(&gates, None) });
+ }
+ for _ in 0..blocking {
+ let gates = Arc::clone(&gates);
+ handle.spawn_blocking(move || run(&gates, None));
+ }
+ run(&gates, Some(handle))
+}
+
+/// Returns all free memory of all threads to the OS. Must run on the thread
+/// that called `Runtime::block_on`, outside the timed part of an iteration.
+pub(super) fn reset_memory() {
+ // With `snmalloc`, the global allocator is not mimalloc, so a collection
+ // has no effect.
+ if !cfg!(all(
+ feature = "mimalloc",
+ feature = "mimalloc_extended",
+ not(feature = "snmalloc")
+ )) {
+ panic!(
+ "--reset-memory requires the features `mimalloc` and
`mimalloc_extended`, \
+ without `snmalloc`"
+ );
+ }
+ let handle = Handle::current();
+ let workers = handle.metrics().num_workers();
+ let blocking = THREADS.load(Ordering::SeqCst).saturating_sub(workers);
+ if !on_every_thread(&handle, workers, blocking, TIMEOUT, collect) {
+ eprintln!("--reset-memory: a thread was busy, the reset is
incomplete");
+ }
+ collect();
+}
+
+#[cfg(all(feature = "mimalloc", feature = "mimalloc_extended"))]
+fn collect() {
+ // SAFETY: `mi_collect` has no preconditions.
Review Comment:
maybe this sould help to point out that `mi_collect` basically returns state
to the OS?
##########
benchmarks/src/util/reset.rs:
##########
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF)
under one or more contributor license agreements
+
+//! Returns memory to the OS between iterations, so that the speed of an
+//! iteration does not depend on what ran before it.
+//!
+//! mimalloc can collect only the heap of the calling thread, so
[`reset_memory`]
+//! runs a collection on every thread of the Tokio runtime:
+//!
+//! ```text
+//! each thread: arrive ── collect ── arrive ── collect ── arrive
+//! │ │
+//! │ └ frees memory that another thread
+//! │ owned and released in round one
+//! └ holds the thread, so no thread runs two of the tasks
+//! ```
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::Duration;
+
+use datafusion_common::instant::Instant;
+use tokio::runtime::{Builder, Handle, Runtime};
+
+/// Longest wait for a busy thread. An idle runtime needs milliseconds.
+const TIMEOUT: Duration = Duration::from_secs(2);
+
+/// How often the main thread wakes workers while it waits.
+const NUDGE_INTERVAL: Duration = Duration::from_millis(1);
+
+/// Worker and blocking threads of the runtime that [`build_runtime`] returns.
+static THREADS: AtomicUsize = AtomicUsize::new(0);
+
+/// Builds the multi-threaded runtime that `--reset-memory` needs.
+pub fn build_runtime() -> std::io::Result<Runtime> {
+ Builder::new_multi_thread()
+ .enable_all()
+ .on_thread_start(|| {
+ THREADS.fetch_add(1, Ordering::SeqCst);
+ })
+ .on_thread_stop(|| {
+ THREADS.fetch_sub(1, Ordering::SeqCst);
+ })
+ .build()
+}
+
+/// A barrier that stops waiting at a deadline.
+struct Gate {
+ expected: usize,
+ deadline: Instant,
+ state: Mutex<GateState>,
+ changed: Condvar,
+}
+
+impl Gate {
+ fn new(expected: usize, deadline: Instant) -> Self {
+ Self {
+ expected,
+ deadline,
+ state: Mutex::new(GateState::default()),
+ changed: Condvar::new(),
+ }
+ }
+
+ /// Returns whether all threads arrived before the deadline.
+ ///
+ /// A thread that the timeout releases can run the task of the busy thread.
+ /// That late arrival must not complete the count, so a timeout closes the
+ /// gate for all threads.
+ ///
+ /// A worker takes tasks in batches. It can block here with the task of a
+ /// parked worker in its local queue, and nothing wakes that worker. The
+ /// main thread passes `nudge` to spawn empty tasks, which wake workers
until
+ /// one of them steals the task.
+ fn arrive(&self, nudge: Option<&Handle>) -> bool {
+ let mut state = self.state.lock().unwrap();
+ state.arrived += 1;
+ if state.arrived == self.expected && !state.closed {
+ self.changed.notify_all();
+ return true;
+ }
+ while !state.closed && state.arrived < self.expected {
+ let now = Instant::now();
+ if now >= self.deadline {
+ state.closed = true;
+ self.changed.notify_all();
+ break;
+ }
+ let mut wait = self.deadline - now;
+ if let Some(handle) = nudge {
+ handle.spawn(async {});
+ wait = wait.min(NUDGE_INTERVAL);
+ }
+ (state, _) = self.changed.wait_timeout(state, wait).unwrap();
+ }
+ !state.closed
+ }
+}
+
+#[derive(Default)]
+struct GateState {
+ arrived: usize,
+ closed: bool,
+}
+
+fn on_every_thread(
+ handle: &Handle,
+ workers: usize,
+ blocking: usize,
+ timeout: Duration,
+ action: fn(),
+) -> bool {
+ let deadline = Instant::now() + timeout;
+ let expected = workers + blocking + 1;
+ let gates: Arc<[Gate; 3]> =
Review Comment:
This is some crazy magic to me -- why are there 3 gates? What is this
implementing? It seems like this is just trying to run a future on each thread?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]