Skip to content

Instantly share code, notes, and snippets.

@aam
Last active March 26, 2024 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aam/45daca2cb25e686bb0a2e9d956c49b69 to your computer and use it in GitHub Desktop.
Save aam/45daca2cb25e686bb0a2e9d956c49b69 to your computer and use it in GitHub Desktop.
Running 8 isolates results in ~3x speedup on JIT
import 'dart:math';
import 'dart:io';
import 'dart:isolate';
CountHits(List args) {
print('${Isolate.current.debugName} $args');
final from = args[0] as int;
final to = args[1] as int;
final sendPort = args[2] as SendPort;
var hits = 0;
var comparisons = 0;
for (int i = from; i <= to; i++) {
for (int j = 1; j <= i; j++) {
if (i == (j * log(j)).round()) {
hits++;
}
comparisons++;
}
}
sendPort.send([hits, comparisons]);
}
main(List<String> args) async {
if (args.length == 0) {
print('${Platform.executable} ${Platform.script} nIsolates batchSize');
return;
}
int nIsolates = int.parse(args[0]);
int batchSize = int.parse(args[1]);
final rps = List.generate(nIsolates, (i) => ReceivePort());
for (int i = 0; i < nIsolates; i++) {
Isolate.spawn(CountHits, [i * batchSize + 1, (i + 1) * batchSize, rps[i].sendPort]);
}
final result = await Future.wait(rps.map((rp) => rp.first));
print(result);
print(result.fold(0, (sum, v) => ((sum as int) + v[0])));
print(result.fold(0, (sum, v) => ((sum as int) + v[1])));
}
@aam
Copy link
Author

aam commented Mar 26, 2024

$ time dart --timeline_streams=all --timeline-recorder=file crunch.dart 1 40000
CountHits [1, 40000, SendPort]
[[4725, 800020000]]
4725
800020000
dart --timeline_streams=all --timeline-recorder=file 1 23.21s user 0.16s system 101% cpu 23.089 total

$ time dart --timeline_streams=all --timeline-recorder=file crunch.dart 8 5000
CountHits [35001, 40000, SendPort]
CountHits [15001, 20000, SendPort]
CountHits [25001, 30000, SendPort]
CountHits [10001, 15000, SendPort]
CountHits [30001, 35000, SendPort]
CountHits [1, 5000, SendPort]
CountHits [20001, 25000, SendPort]
CountHits [5001, 10000, SendPort]
[[752, 12502500], [628, 37502500], [594, 62502500], [573, 87502500], [559, 112502500], [548, 137502500], [539, 162502500], [532, 187502500]]
4725
800020000
dart --timeline_streams=all --timeline-recorder=file 8 24.47s user 0.22s system 399% cpu 6.172 total

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment