Skip to content

Commit

Permalink
benchmark tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanlott committed May 16, 2023
1 parent 7030aab commit 4895775
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
7 changes: 6 additions & 1 deletion pkg/orderbook/orderbook.go
Expand Up @@ -292,7 +292,12 @@ func greedy(
}

// MatchOrders is an alternative approach to order matching that
// works by aligning two opposing sorted slices of Orders.
// works by aligning two opposing sorted slices of Orders then
// iterating through them to generate matches.
// * It generates multiple matches for a buy order until all
// matching sell options are exhausted,
// * When it exhausts all f it ratchets up the buy index again and finds all matching
// orders.
func MatchOrders(buyOrders []Order, sellOrders []Order) []Match {
sort.Slice(buyOrders, func(i, j int) bool {
return buyOrders[i].Price > buyOrders[j].Price
Expand Down
20 changes: 14 additions & 6 deletions pkg/orderbook/orderbook_test.go
Expand Up @@ -3,6 +3,7 @@ package orderbook
import (
"context"
"fmt"
"log"
"math/rand"
"sync"
"testing"
Expand Down Expand Up @@ -322,26 +323,33 @@ func TestAttemptFill(t *testing.T) {
}

func TestMatchOrders(t *testing.T) {
buy, sell := newTestOrders(t, 1000)
buy, sell := newTestOrders(1000)
got := MatchOrders(buy, sell)
for _, match := range got {
t.Logf("\nmatch: [buy] %+v\n [sell] %+v\n", match.Buy, match.Sell)
}
}

func newTestOrders(t *testing.T, count int) (buyOrders []Order, sellOrders []Order) {
func BenchmarkMatchOrder(b *testing.B) {
buy, sell := newTestOrders(b.N)
got := MatchOrders(buy, sell)
fmt.Printf("got #: %v\n", len(got))
}

func newTestOrders(count int) (buyOrders []Order, sellOrders []Order) {
log.Printf("count %d", count)
rand.Seed(time.Now().UnixNano())

min := 100
max := 10000
var minPrice, maxPrice = 100, 10_000
var minOpen, maxOpen = 10, 1_000_000

for i := 0; i < count; i++ {
o := Order{
ID: fmt.Sprintf("%d", i),
AccountID: "", // TODO: add a random account owner
Kind: "market",
Price: uint64(rand.Intn(max-min) + min),
Open: uint64(rand.Intn(max-min) + min),
Price: uint64(rand.Intn(maxPrice-minPrice) + minPrice),
Open: uint64(rand.Intn(maxOpen-minOpen) + minOpen),
Filled: 0,
History: []Match{}, // history should be nil
}
Expand Down

0 comments on commit 4895775

Please sign in to comment.