Skip to content

Instantly share code, notes, and snippets.

@astashov
Last active August 29, 2015 14:18
Show Gist options
  • Save astashov/c0510538847f4d48e8eb to your computer and use it in GitHub Desktop.
Save astashov/c0510538847f4d48e8eb to your computer and use it in GitHub Desktop.
Dart isolates benchmarking
// It seems like it takes ~60-100ms to create an isolate and 20-30ms to send messages over a
// cold port on my Macbook Pro. Once ports are warmed up, it works way faster, especially sending
// from the isolate to the main process - 0-1ms. By some reason, sending a message from the main
// process to isolate fluctuates way more - 0-10ms.
import 'dart:isolate';
import 'dart:async';
import 'package:isols/src/logging.dart';
import 'package:logging/logging.dart';
var _logger = new Logger("main");
main() async {
initialize();
var result = await Future.wait(getValues(10).map((v) {
_logger.info("Running isolate");
return runIsolate(calc, v, (isolate, msg, completer) {
_logger.info("Received a result");
completer.complete(msg);
});
}));
print(result);
}
void calc(SendPort sender) {
//initialize();
runInIsolate(sender, (data) {
//_logger.info("Calculating a result");
sender.send(data * 2);
});
}
Iterable<int> getValues(int max) {
var values = [];
for (var i = 0; i < max; i += 1) {
values.add(i);
}
return values;
}
Future runIsolate(Function isolateFunction, input, void callback(Isolate isolate, message, Completer completer)) {
var receivePort = new ReceivePort();
var completer = new Completer();
new Future(() {
return Isolate.spawn(isolateFunction, receivePort.sendPort).then((isolate) {
_logger.info("Isolate initialized");
receivePort.listen((msg) {
if (msg is SendPort) {
_logger.info("Received a send port from isolate, sending the input now");
msg.send(input);
} else {
callback(isolate, msg, completer);
}
});
});
});
return completer.future.then((v) {
receivePort.close();
return v;
});
}
void runInIsolate(SendPort sender, void callback(data)) {
var receivePort = new ReceivePort();
sender.send(receivePort.sendPort);
receivePort.listen((data) {
callback(data);
receivePort.close();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment