|
| 1 | +import AsyncAlgorithms |
| 2 | + |
| 3 | +@available(macOS 15.0, *) |
| 4 | +@main |
| 5 | +struct Example { |
| 6 | + static func main() async throws { |
| 7 | + let durationUnboundedMPSC = await ContinuousClock().measure { |
| 8 | + await testMPSCChannel(count: 1000000, backpressureStrategy: .unbounded()) |
| 9 | + } |
| 10 | + print("Unbounded MPSC:", durationUnboundedMPSC) |
| 11 | + let durationHighLowMPSC = await ContinuousClock().measure { |
| 12 | + await testMPSCChannel(count: 1000000, backpressureStrategy: .watermark(low: 100, high: 500)) |
| 13 | + } |
| 14 | + print("HighLow MPSC:", durationHighLowMPSC) |
| 15 | + let durationAsyncStream = await ContinuousClock().measure { |
| 16 | + await testAsyncStream(count: 1000000) |
| 17 | + } |
| 18 | + print("AsyncStream:", durationAsyncStream) |
| 19 | + } |
| 20 | + |
| 21 | + static func testMPSCChannel( |
| 22 | + count: Int, |
| 23 | + backpressureStrategy: MultiProducerSingleConsumerChannel<Int, Never>.Source.BackpressureStrategy |
| 24 | + ) async { |
| 25 | + await withTaskGroup { group in |
| 26 | + let channelAndSource = MultiProducerSingleConsumerChannel.makeChannel( |
| 27 | + of: Int.self, |
| 28 | + backpressureStrategy: backpressureStrategy |
| 29 | + ) |
| 30 | + var channel = channelAndSource.channel |
| 31 | + var source = Optional.some(consume channelAndSource.source) |
| 32 | + |
| 33 | + group.addTask { |
| 34 | + var source = source.take()! |
| 35 | + for i in 0..<count { |
| 36 | + try! await source.send(i) |
| 37 | + } |
| 38 | + source.finish() |
| 39 | + } |
| 40 | + |
| 41 | + var counter = 0 |
| 42 | + while let element = await channel.next() { |
| 43 | + counter = element |
| 44 | + } |
| 45 | + print(counter) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + static func testAsyncStream(count: Int) async { |
| 50 | + await withTaskGroup { group in |
| 51 | + let (stream, continuation) = AsyncStream.makeStream(of: Int.self, bufferingPolicy: .unbounded) |
| 52 | + |
| 53 | + group.addTask { |
| 54 | + for i in 0..<count { |
| 55 | + continuation.yield(i) |
| 56 | + } |
| 57 | + continuation.finish() |
| 58 | + } |
| 59 | + |
| 60 | + var counter = 0 |
| 61 | + for await element in stream { |
| 62 | + counter = element |
| 63 | + } |
| 64 | + print(counter) |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments