| 1 |
package nebula |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
func TestScheduler_PooledReuse(t *testing.T) { |
| 10 |
ctx, cancel := context.WithCancel(context.Background()) |
| 11 |
defer cancel() |
| 12 |
|
| 13 |
s := NewScheduler[int](16) |
| 14 |
delivered := make(chan int, 256) |
| 15 |
go s.Run(ctx, func(item int) { delivered <- item }) |
| 16 |
|
| 17 |
const N = 100 |
| 18 |
for i := 0; i < N; i++ { |
| 19 |
s.Schedule(ctx, i, time.Millisecond) |
| 20 |
} |
| 21 |
|
| 22 |
deadline := time.After(2 * time.Second) |
| 23 |
got := 0 |
| 24 |
for got < N { |
| 25 |
select { |
| 26 |
case <-delivered: |
| 27 |
got++ |
| 28 |
case <-deadline: |
| 29 |
t.Fatalf("only %d/%d items delivered", got, N) |
| 30 |
} |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
// BenchmarkScheduler_Schedule reports allocations per Schedule call. |
| 35 |
// In steady state the Scheduler's sync.Pool means we should see zero allocs per op once the pool warms up. |
| 36 |
func BenchmarkScheduler_Schedule(b *testing.B) { |
| 37 |
ctx, cancel := context.WithCancel(context.Background()) |
| 38 |
defer cancel() |
| 39 |
|
| 40 |
s := NewScheduler[int](b.N) |
| 41 |
go s.Run(ctx, func(int) {}) |
| 42 |
|
| 43 |
b.ReportAllocs() |
| 44 |
b.ResetTimer() |
| 45 |
for i := 0; i < b.N; i++ { |
| 46 |
s.Schedule(ctx, i, time.Microsecond) |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// BenchmarkBareAfterFunc is the comparison baseline. |
| 51 |
// What we'd pay per Schedule if Punchy called time.AfterFunc directly without the pooled Scheduler. |
| 52 |
// Allocates a *time.Timer plus a closure each call. |
| 53 |
func BenchmarkBareAfterFunc(b *testing.B) { |
| 54 |
ctx, cancel := context.WithCancel(context.Background()) |
| 55 |
defer cancel() |
| 56 |
|
| 57 |
queue := make(chan int, b.N) |
| 58 |
go func() { |
| 59 |
for { |
| 60 |
select { |
| 61 |
case <-ctx.Done(): |
| 62 |
return |
| 63 |
case <-queue: |
| 64 |
} |
| 65 |
} |
| 66 |
}() |
| 67 |
|
| 68 |
b.ReportAllocs() |
| 69 |
b.ResetTimer() |
| 70 |
for i := 0; i < b.N; i++ { |
| 71 |
i := i |
| 72 |
time.AfterFunc(time.Microsecond, func() { |
| 73 |
select { |
| 74 |
case queue <- i: |
| 75 |
case <-ctx.Done(): |
| 76 |
} |
| 77 |
}) |
| 78 |
} |
| 79 |
} |