Skip to content
Closed
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## Next

* internal: updates `matchers` dev-dependency (#394).
* Add `PriorityQueue` (#392).
* Add support for Weak references (#388).
* Clarify difference between `List` and `pure/List` in doc comments (#386).

Expand Down
226 changes: 226 additions & 0 deletions bench/PriorityQueues.bench.mo
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
import Bench "mo:bench";

import Array "../src/Array";
import Nat "../src/Nat";
import PriorityQueue "../src/PriorityQueue";
import PriorityQueueSet "utils/PriorityQueueSet";
import Random "../src/Random";
import Runtime "../src/Runtime";
import Map "../src/Map";
import Text "../src/Text";

module {

type PriorityQueueUpdateOperation<T> = {
#Push : T;
#Pop;
#Clear
};

// Generates a randomized sequence of PriorityQueueUpdateOperations on Nat values.
// The distribution of operations is controlled by weights.
//
// randomSeed - seed for reproducible RNG
// operationsCount – total number of operations to generate
// maxValueExclusive – upper bound (exclusive) for values pushed into the queue
// wPush – relative weight of #Push operations (values in [0, maxValueExclusive))
// wPop – relative weight of #Pop operations
// wClear – relative weight of #Clear operations
func genOpsNatRandom(
randomSeed : Nat64,
operationsCount : Nat,
maxValueExclusive : Nat,
wPush : Nat,
wPop : Nat,
wClear : Nat
) : [PriorityQueueUpdateOperation<Nat>] {
let rng = Random.seed(randomSeed);
Array.tabulate<PriorityQueueUpdateOperation<Nat>>(
operationsCount,
func(_) {
let aux = rng.natRange(0, wPush + wPop + wClear);
if (aux < wPush) {
#Push(rng.natRange(0, maxValueExclusive))
} else if (aux < wPush + wPop) {
#Pop
} else {
#Clear
}
}
)
};

// Generates a sequence of PriorityQueueUpdateOperations on Nat values:
// 1. pushOperationsCount pushes, followed by
// 2. pushOperationsCount pops.
//
// randomSeed - seed for reproducible RNG
// pushOperationsCount – total number of push operations to generate
// maxValueExclusive – upper bound (exclusive) for values pushed into the queue
func genOpsPushThenPop(
randomSeed : Nat64,
pushOperationsCount : Nat,
maxValueExclusive : Nat
) : [PriorityQueueUpdateOperation<Nat>] {
let rng = Random.seed(randomSeed);
Array.tabulate<PriorityQueueUpdateOperation<Nat>>(
2 * pushOperationsCount,
func(i) {
switch (i < pushOperationsCount) {
case true #Push(rng.natRange(0, maxValueExclusive));
case false #Pop
}
}
)
};

// Generates a sequence of PriorityQueueUpdateOperations on Nat values:
// 1. size pushes, followed by
// 2. popPushCount instances of a pop followed by a push.
//
// randomSeed - seed for reproducible RNG
// size – initial size
// popPushCount - number of times to pop and then push
// maxValueExclusive – upper bound (exclusive) for values pushed into the queue
func genOpsKeepConstantSize(
randomSeed : Nat64,
size : Nat,
popPushCount : Nat,
maxValueExclusive : Nat
) : [PriorityQueueUpdateOperation<Nat>] {
let rng = Random.seed(randomSeed);
Array.tabulate<PriorityQueueUpdateOperation<Nat>>(
size + 2 * popPushCount,
func(i) {
if (i < size or (i - size) % 2 == 1) {
#Push(rng.natRange(0, maxValueExclusive))
} else {
#Pop
}
}
)
};

public func init() : Bench.Bench {
let bench = Bench.Bench();

bench.name("Different priority queue implementations");
bench.description("Compare the performance of the following priority queue implementations:
- `PriorityQueue`: Binary heap implementation over `List`.
- `PriorityQueueSet`: Wrapper over `Set<(T, Nat)>`.");

let testInstances : Map.Map<Text, [PriorityQueueUpdateOperation<Nat>]> = Map.fromIter(
[
(
"1.) 100000 operations (push:pop = 1:1)",
genOpsNatRandom(
/* randomSeed = */ 23,
/* operationsCount = */ 100000,
/* maxValueExclusive = */ 100000,
/* wPush = */ 1,
/* wPop = */ 1,
/* wClear = */ 0
)
),
(
"2.) 100000 operations (push:pop = 2:1)",
genOpsNatRandom(
/* randomSeed = */ 24,
/* operationsCount = */ 100000,
/* maxValueExclusive = */ 100000,
/* wPush = */ 2,
/* wPop = */ 1,
/* wClear = */ 0
)
),
(
"3.) 100000 operations (push:pop = 10:1)",
genOpsNatRandom(
/* randomSeed = */ 42,
/* operationsCount = */ 100000,
/* maxValueExclusive = */ 100000,
/* wPush = */ 10,
/* wPop = */ 1,
/* wClear = */ 0
)
),
(
"4.) 100000 operations (only push)",
genOpsNatRandom(
/* randomSeed = */ 33,
/* operationsCount = */ 100000,
/* maxValueExclusive = */ 100000,
/* wPush = */ 1,
/* wPop = */ 0,
/* wClear = */ 0
)
),
(
"5.) 50000 pushes, then 50000 pops",
genOpsPushThenPop(
/* randomSeed = */ 13,
/* pushOperationsCount = */ 50000,
/* maxValueExclusive */ 100000
)
),
(
"6.) 50000 pushes, then 25000 \"pop;push\"es",
genOpsKeepConstantSize(
/* randomSeed = */ 55,
/* size = */ 50000,
/* popPushCount = */ 25000,
/* maxValueExclusive = */ 100000
)
)
].values(),
Text.compare
);
bench.rows(Map.keys<Text, [PriorityQueueUpdateOperation<Nat>]>(testInstances) |> Array.fromIter(_));

let testRunners : Map.Map<Text, [PriorityQueueUpdateOperation<Nat>] -> ()> = Map.fromIter(
[
(
"A) PriorityQueue",
func(ops : [PriorityQueueUpdateOperation<Nat>]) {
let priorityQueue = PriorityQueue.empty<Nat>();
for (op in ops.values()) {
switch (op) {
case (#Push element) PriorityQueue.push(priorityQueue, Nat.compare, element);
case (#Pop) ignore PriorityQueue.pop(priorityQueue, Nat.compare);
case (#Clear) PriorityQueue.clear(priorityQueue)
}
}
}
),
(
"B) PriorityQueueSet",
func(ops : [PriorityQueueUpdateOperation<Nat>]) {
let priorityQueueSet = PriorityQueueSet.empty<Nat>();
for (op in ops.values()) {
switch (op) {
case (#Push element) PriorityQueueSet.push(priorityQueueSet, Nat.compare, element);
case (#Pop) ignore PriorityQueueSet.pop(priorityQueueSet, Nat.compare);
case (#Clear) PriorityQueueSet.clear(priorityQueueSet)
}
}
}
)
].values(),
Text.compare
);
bench.cols(Map.keys<Text, [PriorityQueueUpdateOperation<Nat>] -> ()>(testRunners) |> Array.fromIter(_));

bench.runner(
func(row, col) {
switch (
Map.get(testInstances, Text.compare, row),
Map.get(testRunners, Text.compare, col)
) {
case (?ops, ?runner) runner(ops);
case _ Runtime.trap("Missing test instance or runner")
}
}
);
bench
}
}
159 changes: 159 additions & 0 deletions bench/utils/PriorityQueueSet.mo
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/// A mutable priority queue of elements.
/// !!! In contrast to the implementation in `src/PriorityQueue.mo`, this one
/// is a wrapper over `Set`. !!!
///
/// Always returns the element with the highest priority first,
/// as determined by a user-provided comparison function.
///
/// Internally implemented as a wrapper over a core library `Set<(T, Nat)>`.
/// The `Nat` values serve as unique tags to distinguish elements
/// with equal priority, since a `Set` cannot store duplicates.
///
/// Performance:
/// * Runtime: `O(log n)` for `push`, `pop` and `peek`.
/// * Runtime: `O(1)` for `clear`, `size`, and `isEmpty`.
/// * Space: `O(n)`, where `n` is the number of stored elements.
import Set "../../src/Set";
import Order "../../src/Order";
import Nat "../../src/Nat";
import { Tuple2 } "../../src/Tuples";

module {
public type PriorityQueue<T> = {
set : Set.Set<(T, Nat)>;
var counter : Nat
};

/// Returns an empty priority queue.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
///
/// let pq = PriorityQueue.empty<Nat>();
/// assert PriorityQueue.isEmpty(pq);
/// ```
///
/// Runtime: `O(1)`. Space: `O(1)`.
public func empty<T>() : PriorityQueue<T> = {
set = Set.empty<(T, Nat)>();
var counter = 0
};

/// Returns a priority queue containing a single element.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
///
/// let pq = PriorityQueue.singleton<Nat>(42);
/// assert PriorityQueue.peek(pq) == ?42;
/// ```
///
/// Runtime: `O(1)`. Space: `O(1)`.
public func singleton<T>(element : T) : PriorityQueue<T> = {
set = Set.singleton((element, 0));
var counter = 1
};

/// Returns the number of elements in the priority queue.
///
/// Runtime: `O(1)`.
public func size<T>(priorityQueue : PriorityQueue<T>) : Nat = Set.size(priorityQueue.set);

/// Returns `true` iff the priority queue is empty.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
/// import Nat "mo:core/Nat";
///
/// let pq = PriorityQueue.empty<Nat>();
/// assert PriorityQueue.isEmpty(pq);
/// PriorityQueue.push(pq, Nat.compare, 5);
/// assert not PriorityQueue.isEmpty(pq);
/// ```
///
/// Runtime: `O(1)`. Space: `O(1)`.
public func isEmpty<T>(priorityQueue : PriorityQueue<T>) : Bool = Set.isEmpty(priorityQueue.set);

/// Removes all elements from the priority queue.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
/// import Nat "mo:core/Nat";
///
/// let pq = PriorityQueue.empty<Nat>();
/// PriorityQueue.push(pq, Nat.compare, 5);
/// PriorityQueue.push(pq, Nat.compare, 10);
/// assert not PriorityQueue.isEmpty(pq);
/// PriorityQueue.clear(pq);
/// assert PriorityQueue.isEmpty(pq);
/// ```
///
/// Runtime: `O(1)`. Space: `O(1)`.
public func clear<T>(priorityQueue : PriorityQueue<T>) = Set.clear(priorityQueue.set);

/// Inserts a new element into the priority queue.
///
/// `compare` – comparison function that defines priority ordering.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
/// import Nat "mo:core/Nat";
///
/// let pq = PriorityQueue.empty<Nat>();
/// PriorityQueue.push(pq, Nat.compare, 5);
/// PriorityQueue.push(pq, Nat.compare, 10);
/// assert PriorityQueue.peek(pq) == ?10;
/// ```
///
/// Runtime: `O(log n)`. Space: `O(log n)`.
public func push<T>(priorityQueue : PriorityQueue<T>, compare : (T, T) -> Order.Order, element : T) {
Set.add(priorityQueue.set, Tuple2.makeCompare(compare, Nat.compare), (element, priorityQueue.counter));
priorityQueue.counter += 1
};

/// Returns the element with the highest priority, without removing it.
/// Returns `null` if the queue is empty.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
/// import Nat "mo:core/Nat";
///
/// let pq = PriorityQueue.singleton<Nat>(42);
/// assert PriorityQueue.peek(pq) == ?42;
/// ```
///
/// Runtime: `O(log n)`. Space: `O(1)`.
public func peek<T>(priorityQueue : PriorityQueue<T>) : ?T = do ? {
let (element, _) = Set.max(priorityQueue.set)!;
element
};

/// Removes and returns the element with the highest priority.
/// Returns `null` if the queue is empty.
///
/// `compare` – comparison function that defines priority ordering.
///
/// Example:
/// ```motoko
/// import PriorityQueue "mo:core/internal/PriorityQueueSet";
/// import Nat "mo:core/Nat";
///
/// let pq = PriorityQueue.empty<Nat>();
/// PriorityQueue.push(pq, Nat.compare, 5);
/// PriorityQueue.push(pq, Nat.compare, 10);
/// assert PriorityQueue.pop(pq, Nat.compare) == ?10;
/// ```
///
/// Runtime: `O(log n)`. Space: `O(log n)`.
public func pop<T>(priorityQueue : PriorityQueue<T>, compare : (T, T) -> Order.Order) : ?T = do ? {
let (element, nonce) = Set.max(priorityQueue.set)!;
Set.remove(priorityQueue.set, Tuple2.makeCompare(compare, Nat.compare), (element, nonce));
element
}
}
Loading