Skip to content

Instantly share code, notes, and snippets.

@simolus3
Last active March 31, 2020 14:51
Show Gist options
  • Save simolus3/a7c5e65a107b30b60911c8648345b448 to your computer and use it in GitHub Desktop.
Save simolus3/a7c5e65a107b30b60911c8648345b448 to your computer and use it in GitHub Desktop.
Benchmark of number length testing
import 'dart:math';
import 'dart:typed_data';
import 'package:benchmark_harness/benchmark_harness.dart';
const length = 1000000;
final inputs = Int64List(length);
class WithLog extends BenchmarkBase {
WithLog() : super('log');
final log10 = log(10);
@override
void run() {
for (var i = 0; i < length; i++) {
(log(inputs[i]) / log10).floor() + 1;
}
}
}
class WithToString extends BenchmarkBase {
WithToString() : super('toString');
@override
void run() {
for (var i = 0; i < length; i++) {
inputs[i].toString().length;
}
}
}
void main() {
final rng = Random();
const maxForNextInt = 1 << 32;
for (var i = 0; i < length; i++) {
// << 31 so we're always positive
inputs[i] = (rng.nextInt(maxForNextInt) << 31) | rng.nextInt(maxForNextInt);
}
WithLog().report();
WithToString().report();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment