Skip to content

Instantly share code, notes, and snippets.

@lrhn
Created July 30, 2019 16:39
Show Gist options
  • Save lrhn/bcc51424ceb562ef115ea634a8de9f07 to your computer and use it in GitHub Desktop.
Save lrhn/bcc51424ceb562ef115ea634a8de9f07 to your computer and use it in GitHub Desktop.
Await Benchrmark
import "dart:async";
const NeverInline = "NeverInline";
Future<double> measureForSync(void fun()) async {
int c = 0;
int e = 0;
final sw = Stopwatch()..start();
do {
fun();
e = sw.elapsedMilliseconds;
c++;
} while (e < 2000);
return c/e;
}
Future<double> measureForAsync(FutureOr fun()) async {
int c = 0;
int e = 0;
final sw = Stopwatch()..start();
do {
await fun();
e = sw.elapsedMilliseconds;
c++;
} while (e < 2000);
return c/e;
}
@NeverInline
int fooSync() => 0;
@NeverInline
FutureOr<int> fooFutureOr() => 0;
@NeverInline
Future<int> fooFuture() => Future.value(0);
@NeverInline
Future<int> fooAsync() async => 0;
main() async {
for (var i = 0; i < 5; i++) {
var d = 0.0;
d = await measureForSync(fooSync);
print("fooSync, No await: $d /ms");
await new Future(()=>0);
d = await measureForAsync(fooSync);
print("fooSync, awaited: $d /ms");
await new Future(()=>0);
d = await measureForSync(fooFutureOr);
print("fooFutureOr, No await: $d /ms");
await new Future(()=>0);
d = await measureForAsync(fooFutureOr);
print("fooFutureOr, awaited: $d /ms");
await new Future(()=>0);
d = await measureForSync(fooFuture);
print("fooFuture, No await: $d /ms");
await new Future(()=>0);
d = await measureForAsync(fooFuture);
print("fooFuture, awaited: $d /ms");
await new Future(()=>0);
d = await measureForSync(fooAsync);
print("fooAsync, No await: $d /ms");
await new Future(()=>0);
d = await measureForAsync(fooAsync);
print("fooAsync, awaited: $d /ms");
await new Future(()=>0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment