-
Beta Was this translation helpful? Give feedback.
Answered by
ilopX
Jun 18, 2021
Replies: 1 comment 4 replies
-
Hi @kirill-21! Benchmark code
import 'dart:ffi';
import 'package:win32/win32.dart';
void main() {
final benchmarks = runAllBenchmarks(passes: 100000);
printAll(benchmarks);
}
List<Benchmark> runAllBenchmarks({required int passes}) {
final defaultFuncName = 'GetAsyncKeyState()';
final memorizedFuncName = 'MemorizedGetAsyncKeyState()';
final key = 45 & 0x8000;
return [
Benchmark(defaultFuncName, 'load & first call', () {
GetAsyncKeyState(key);
}),
Benchmark(defaultFuncName, 'second call', () {
GetAsyncKeyState(key);
}),
Benchmark(defaultFuncName, 'third call', () {
GetAsyncKeyState(key);
}),
Benchmark(memorizedFuncName, 'load', () {
loadOptimizedGetAsyncKeyState();
}),
Benchmark(memorizedFuncName, 'first call', () {
MemorizedGetAsyncKeyState(key);
}),
Benchmark(memorizedFuncName, 'second call', () {
MemorizedGetAsyncKeyState(key);
}),
Benchmark(memorizedFuncName, 'third call', () {
MemorizedGetAsyncKeyState(key);
}),
Benchmark(defaultFuncName, 'calls($passes)', () {
for (var i = 0; i < passes; i++) {
GetAsyncKeyState(key);
}
}),
Benchmark(memorizedFuncName, 'calls($passes)', () {
for (var i = 0; i < passes; i++) {
MemorizedGetAsyncKeyState(key);
}
}),
];
}
void printAll(List<Benchmark> benchmarks) {
for (var i = 0; i < benchmarks.length; i++) {
final isLastBenchmark = i == benchmarks.length - 1;
final benchmarkText = benchmarks[i].toPrintableString(
renderBiceps: isLastBenchmark,
);
print(benchmarkText);
if (i == 2 || i == 6) {
print('');
}
}
}
late DynamicLibrary _user32;
late int Function(int vKey) _memorizedAsyncKeyState;
void loadOptimizedGetAsyncKeyState() {
_user32 = DynamicLibrary.open('user32.dll');
_memorizedAsyncKeyState = _user32.lookupFunction<Int16 Function(Int32 vKey),
int Function(int vKey)>('GetAsyncKeyState');
}
int MemorizedGetAsyncKeyState(int vKey) {
return _memorizedAsyncKeyState(vKey);
}
class Benchmark {
final String name;
final String effect;
late final double timeMs;
Benchmark(
this.name,
this.effect,
void Function() func,
) {
final stopwatch = Stopwatch()..start();
func();
stopwatch.stop();
timeMs = (stopwatch.elapsedTicks / 10000);
}
String toPrintableString({bool renderBiceps = false}) {
final fName = name.padRight(32);
final fEffect = effect.padLeft(18);
final fTimeMs = timeMs.toStringAsFixed(4).padLeft(12);
final biceps = renderBiceps ? _greenText('💪') : '';
return '$fName$fEffect${_blueText(fTimeMs)} ms $biceps';
}
String _blueText(String text) {
return '\x1B[34m$text\x1B[0m';
}
String _greenText(String text) {
return '\x1B[32m$text\x1B[0m';
}
} |
Beta Was this translation helpful? Give feedback.
4 replies
Answer selected by
krll-kov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @kirill-21!
Here is my benchmark.
Optimization works, 💪 but only slightly.
My results
Benchmark code