Skip to content

Commit 1251307

Browse files
committed
add async benchmark
1 parent f6db47e commit 1251307

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Samples/SwiftJavaExtractJNISampleApp/Sources/MySwiftLibrary/Async.swift

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,28 @@ public func asyncCopy(myClass: MySwiftClass) async throws -> MySwiftClass {
2828
try await Task.sleep(for: .milliseconds(500))
2929
return new
3030
}
31+
32+
public func asyncRunningSum() async -> Int64 {
33+
let totalSum = await withTaskGroup(of: Int64.self) { group in
34+
// 1. Add child tasks to the group
35+
for number in stride(from: Int64(1), through: 100, by: 1) {
36+
group.addTask {
37+
try? await Task.sleep(for: .milliseconds(number))
38+
return number
39+
}
40+
}
41+
42+
var collectedSum: Int64 = 0
43+
44+
// `for await ... in group` loops as each child task completes,
45+
// (not necessarily in the order they were added).
46+
for await number in group {
47+
collectedSum += number
48+
}
49+
50+
return collectedSum
51+
}
52+
53+
// This is the value returned by the `withTaskGroup` closure.
54+
return totalSum
55+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2025 Apple Inc. and the Swift.org project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of Swift.org project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
package com.example.swift;
16+
17+
import org.openjdk.jmh.annotations.*;
18+
import org.openjdk.jmh.infra.Blackhole;
19+
import org.swift.swiftkit.core.ClosableSwiftArena;
20+
import org.swift.swiftkit.core.ConfinedSwiftMemorySession;
21+
import org.swift.swiftkit.core.SwiftArena;
22+
23+
import java.util.ArrayList;
24+
import java.util.List;
25+
import java.util.Optional;
26+
import java.util.OptionalInt;
27+
import java.util.concurrent.TimeUnit;
28+
29+
@BenchmarkMode(Mode.AverageTime)
30+
@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS)
31+
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
32+
@OutputTimeUnit(TimeUnit.SECONDS)
33+
@Fork(value = 3, jvmArgsAppend = { "--enable-native-access=ALL-UNNAMED" })
34+
public class AsyncBenchmark {
35+
36+
@Benchmark
37+
public long asyncSum() {
38+
return MySwiftLibrary.asyncRunningSum().join();
39+
}
40+
}

0 commit comments

Comments
 (0)