Skip to content

Instantly share code, notes, and snippets.

@mraleph
Created June 10, 2021 11:44
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 mraleph/3ee317f68f1215faa2c471142143a707 to your computer and use it in GitHub Desktop.
Save mraleph/3ee317f68f1215faa2c471142143a707 to your computer and use it in GitHub Desktop.
void main() {
final count = 1000000;
final names = ['good', 'bad', 'whatever'];
final tests = [_test1, _test2, _test3];
final sw = Stopwatch();
var repeat = 10;
sw.start();
while (repeat-- > 0) {
for (var i = 0; i < tests.length; i++) {
final name = names[i];
final test = tests[i];
final seconds = (sw.elapsedMilliseconds / 1000).toStringAsFixed(3);
final title = 'Time passed: $seconds, Test \'$name\'';
_measure(title, 1, () => test(count));
}
}
}
void _measure(String name, int count, Function() f) {
final sw = Stopwatch();
sw.start();
for (var i = 0; i < count; i++) {
f();
}
sw.stop();
final time = sw.elapsedMicroseconds / 1000;
print('$name: $time ms');
}
int add(int x, int y) => x + y;
int add2(int Function(int x, int y) f, int x, int y) => f(x, y);
int sub(int x, int y) => x - y;
void _test1(int count) {
for (var i = 0; i < count; i++) {
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
add(1, 2);
}
}
void _test2(int count) {
final sumIt = sum(add);
for (var i = 0; i < count; i++) {
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
}
}
void _test3(int count) {
final sumIt = sum(sub);
for (var i = 0; i < count; i++) {
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
sumIt(1, 2);
}
}
int Function(int, int) sum(int Function(int, int) f) {
return (x, y) {
return x + y + f(x, y);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment