Merge pull request '优化撮合与集合竞价,提供可复现的性能基准' (#3) from codex/trading-performance into main
Reviewed-on: #3
This commit was merged in pull request #3.
This commit is contained in:
@@ -33,3 +33,12 @@ sequenceDiagram
|
|||||||
B->>B: 丢弃计划,保持原有盘口
|
B->>B: 丢弃计划,保持原有盘口
|
||||||
end
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 吞吐基准
|
||||||
|
|
||||||
|
在获准的测量机器上执行 `cargo run --release --locked -p matching --example throughput`。用同一工具链、硬件和负载对比基线 ca45f83 与本分支,在基线工作区放入同一个 examples/throughput.rs。程序预热后分别报告七轮的中位和最佳 ops/s,包括无交叉、单笔、扫 32 单、写入并撮合移除一张单,以及 8192 单集合竞价。前三项使用固定盘口,写入场景在每次迭代中实际维护盘口;开盘场景的单位是整次竞价。均为单线程内存测量,SQLite、网关和网络延迟在范围之外。此次未执行 release 测量。
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
bench["examples/throughput.rs"] -->|驱动固定负载| engine["src/lib.rs"]
|
||||||
|
```
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
//! Single-thread benchmarks. Use the identical file on both revisions.
|
||||||
|
use matching::{Order, OrderBook, Side};
|
||||||
|
use std::{hint::black_box, time::Instant};
|
||||||
|
|
||||||
|
fn order(seq: i64, side: Side, price: i64, remaining: i64) -> Order {
|
||||||
|
Order {
|
||||||
|
seq,
|
||||||
|
side,
|
||||||
|
price,
|
||||||
|
remaining,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn measure(name: &str, iterations: u64, mut run: impl FnMut() -> usize) {
|
||||||
|
for _ in 0..100 {
|
||||||
|
black_box(run());
|
||||||
|
}
|
||||||
|
let mut samples = Vec::new();
|
||||||
|
let mut fills = 0;
|
||||||
|
for _ in 0..7 {
|
||||||
|
let start = Instant::now();
|
||||||
|
fills = 0;
|
||||||
|
for _ in 0..iterations {
|
||||||
|
fills += black_box(run());
|
||||||
|
}
|
||||||
|
samples.push(start.elapsed().as_secs_f64());
|
||||||
|
}
|
||||||
|
samples.sort_by(f64::total_cmp);
|
||||||
|
println!(
|
||||||
|
"{name}: iterations={iterations} fills/sample={fills} median={:.0} ops/s best={:.0} ops/s",
|
||||||
|
iterations as f64 / samples[3],
|
||||||
|
iterations as f64 / samples[0]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fn main() {
|
||||||
|
let mut book = OrderBook::default();
|
||||||
|
for seq in 1..=4096 {
|
||||||
|
book.update(order(seq, Side::Sell, 50 + seq % 10, 1));
|
||||||
|
}
|
||||||
|
for (label, price, qty) in [
|
||||||
|
("miss/plan", 49, 1),
|
||||||
|
("one/plan", 50, 1),
|
||||||
|
("sweep32/plan", 55, 32),
|
||||||
|
] {
|
||||||
|
let bid = order(5000, Side::Buy, price, qty);
|
||||||
|
measure(label, 100_000, || {
|
||||||
|
black_box(&book).match_incoming(black_box(&bid)).len()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut seq = 5000;
|
||||||
|
let mut live = OrderBook::default();
|
||||||
|
measure("maker-insert + taker-fill + maker-remove", 100_000, || {
|
||||||
|
seq += 2;
|
||||||
|
live.update(order(seq, Side::Sell, 50, 1));
|
||||||
|
let fills = live.match_incoming(black_box(&order(seq + 1, Side::Buy, 50, 1)));
|
||||||
|
live.update(order(fills[0].ask, Side::Sell, 50, 0));
|
||||||
|
fills.len()
|
||||||
|
});
|
||||||
|
for seq in 4097..=8192 {
|
||||||
|
book.update(order(seq, Side::Buy, 50 + seq % 10, 1));
|
||||||
|
}
|
||||||
|
measure("opening/8192-orders", 100, || {
|
||||||
|
black_box(&book).opening().len()
|
||||||
|
});
|
||||||
|
}
|
||||||
+111
-16
@@ -32,8 +32,12 @@ impl OrderBook {
|
|||||||
/// Read only the opposite side and stop at the first untouched price level.
|
/// Read only the opposite side and stop at the first untouched price level.
|
||||||
pub fn match_incoming(&self, incoming: &Order) -> Vec<Fill> {
|
pub fn match_incoming(&self, incoming: &Order) -> Vec<Fill> {
|
||||||
match incoming.side {
|
match incoming.side {
|
||||||
Side::Buy => plan(std::iter::once(incoming), self.asks.values(), None),
|
Side::Buy => sweep(incoming, self.asks.values(), |maker| {
|
||||||
Side::Sell => plan(self.bids.values(), std::iter::once(incoming), None),
|
maker.price <= incoming.price
|
||||||
|
}),
|
||||||
|
Side::Sell => sweep(incoming, self.bids.values(), |maker| {
|
||||||
|
maker.price >= incoming.price
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,27 +48,62 @@ impl OrderBook {
|
|||||||
if bid.price < ask.price {
|
if bid.price < ask.price {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
|
// Move each price boundary once as the candidate tick rises.
|
||||||
|
let mut demand: i128 = self.bids.values().map(|o| i128::from(o.remaining)).sum();
|
||||||
|
let mut supply = 0i128;
|
||||||
|
let mut bids = self.bids.values().rev().peekable();
|
||||||
|
let mut asks = self.asks.values().peekable();
|
||||||
let price = (0..=100)
|
let price = (0..=100)
|
||||||
.min_by_key(|&p| {
|
.min_by_key(|&tick| {
|
||||||
let demand: i128 = self
|
while bids.peek().is_some_and(|o| o.price < tick) {
|
||||||
.bids
|
demand -= i128::from(bids.next().unwrap().remaining);
|
||||||
.values()
|
}
|
||||||
.take_while(|o| o.price >= p)
|
while asks.peek().is_some_and(|o| o.price <= tick) {
|
||||||
.map(|o| i128::from(o.remaining))
|
supply += i128::from(asks.next().unwrap().remaining);
|
||||||
.sum();
|
}
|
||||||
let supply: i128 = self
|
(Reverse(demand.min(supply)), (demand - supply).abs(), tick)
|
||||||
.asks
|
|
||||||
.values()
|
|
||||||
.take_while(|o| o.price <= p)
|
|
||||||
.map(|o| i128::from(o.remaining))
|
|
||||||
.sum();
|
|
||||||
(Reverse(demand.min(supply)), (demand - supply).abs(), p)
|
|
||||||
})
|
})
|
||||||
.expect("nonempty tick range");
|
.expect("nonempty tick range");
|
||||||
plan(self.bids.values(), self.asks.values(), Some(price))
|
plan(self.bids.values(), self.asks.values(), Some(price))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sweep<'a>(
|
||||||
|
order: &Order,
|
||||||
|
makers: impl Iterator<Item = &'a Order>,
|
||||||
|
crosses: impl Fn(&Order) -> bool,
|
||||||
|
) -> Vec<Fill> {
|
||||||
|
let mut remaining = order.remaining;
|
||||||
|
let mut fills = Vec::new();
|
||||||
|
for maker in makers {
|
||||||
|
if !crosses(maker) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let quantity = remaining.min(maker.remaining);
|
||||||
|
let (bid, ask) = if order.side == Side::Buy {
|
||||||
|
(order.seq, maker.seq)
|
||||||
|
} else {
|
||||||
|
(maker.seq, order.seq)
|
||||||
|
};
|
||||||
|
let price = if maker.seq < order.seq {
|
||||||
|
maker.price
|
||||||
|
} else {
|
||||||
|
order.price
|
||||||
|
};
|
||||||
|
fills.push(Fill {
|
||||||
|
bid,
|
||||||
|
ask,
|
||||||
|
price,
|
||||||
|
quantity,
|
||||||
|
});
|
||||||
|
remaining -= quantity;
|
||||||
|
if remaining == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fills
|
||||||
|
}
|
||||||
|
|
||||||
fn set<K: Ord>(side: &mut BTreeMap<K, Order>, key: K, order: Order) {
|
fn set<K: Ord>(side: &mut BTreeMap<K, Order>, key: K, order: Order) {
|
||||||
if order.remaining == 0 {
|
if order.remaining == 0 {
|
||||||
side.remove(&key);
|
side.remove(&key);
|
||||||
@@ -117,3 +156,59 @@ pub fn cross(orders: Vec<Order>, phase: Phase) -> Vec<Fill> {
|
|||||||
Phase::Continuous => plan(book.bids.values(), book.asks.values(), None),
|
Phase::Continuous => plan(book.bids.values(), book.asks.values(), None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn opening_agrees_with_exhaustive_price_discovery() {
|
||||||
|
let mut seed = 13u64;
|
||||||
|
for _ in 0..96 {
|
||||||
|
let mut book = OrderBook::default();
|
||||||
|
for seq in 0..64 {
|
||||||
|
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||||
|
book.update(Order {
|
||||||
|
seq,
|
||||||
|
side: if seq % 2 == 0 { Side::Buy } else { Side::Sell },
|
||||||
|
price: ((seed >> 32) % 101) as i64,
|
||||||
|
remaining: 1 + (seed % 17) as i64,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let p = (0..=100)
|
||||||
|
.min_by_key(|&p| {
|
||||||
|
let demand: i64 = book
|
||||||
|
.bids
|
||||||
|
.values()
|
||||||
|
.filter(|o| o.price >= p)
|
||||||
|
.map(|o| o.remaining)
|
||||||
|
.sum();
|
||||||
|
let supply: i64 = book
|
||||||
|
.asks
|
||||||
|
.values()
|
||||||
|
.filter(|o| o.price <= p)
|
||||||
|
.map(|o| o.remaining)
|
||||||
|
.sum();
|
||||||
|
(Reverse(demand.min(supply)), (demand - supply).abs(), p)
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
book.opening(),
|
||||||
|
plan(book.bids.values(), book.asks.values(), Some(p))
|
||||||
|
);
|
||||||
|
for side in [Side::Buy, Side::Sell] {
|
||||||
|
let incoming = Order {
|
||||||
|
seq: 90,
|
||||||
|
side,
|
||||||
|
price: 50,
|
||||||
|
remaining: 16,
|
||||||
|
};
|
||||||
|
let expected = match side {
|
||||||
|
Side::Buy => plan(std::iter::once(&incoming), book.asks.values(), None),
|
||||||
|
Side::Sell => plan(book.bids.values(), std::iter::once(&incoming), None),
|
||||||
|
};
|
||||||
|
assert_eq!(book.match_incoming(&incoming), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user