1
1
import 'dart:isolate' ;
2
2
3
+ import 'package:flutter/foundation.dart' ;
3
4
import 'package:flutter/material.dart' ;
4
5
import 'package:flutter_riverpod/flutter_riverpod.dart' ;
5
6
6
7
enum TestType { createNumbersArray, calculateFactorial }
7
8
8
9
class TestResult {
9
10
final Duration mainThreadExecutionTime;
10
- final Duration anotherThreadExecutionTime;
11
+ final Duration isolateExecutionTime;
12
+ final Duration computeExecutionTime;
11
13
final TestType testType;
12
14
13
15
TestResult ({
14
16
required this .testType,
17
+ required this .computeExecutionTime,
15
18
required this .mainThreadExecutionTime,
16
- required this .anotherThreadExecutionTime ,
19
+ required this .isolateExecutionTime ,
17
20
});
18
21
}
19
22
@@ -27,33 +30,40 @@ class TestsController extends ChangeNotifier {
27
30
isTestRunning = true ;
28
31
notifyListeners ();
29
32
30
- late final Future <void > Function () test;
33
+ late final Future <void > Function (int number) test;
34
+ late final int testNumber;
31
35
32
36
switch (testType) {
33
37
case TestType .createNumbersArray:
34
- test = () => createNumbersArray (10000 );
38
+ test = createNumbersArray;
39
+ testNumber = 10000 ;
35
40
break ;
36
41
case TestType .calculateFactorial:
37
- test = () => calculateFactorial (50 );
42
+ test = calculateFactorial;
43
+ testNumber = 50 ;
38
44
break ;
39
45
}
40
46
41
- final anotherThreadExecutionTime = await measureExecutionTime (
42
- () => workInBackground (
47
+ final isolateExecutionTime = await measureExecutionTime (
48
+ () => workInIsolate (
43
49
(port) async {
44
- await test ();
50
+ await test (testNumber );
45
51
Isolate .exit (port, 'canceled' );
46
52
},
47
53
),
48
54
);
49
55
final mainThreadExecutionTime = await measureExecutionTime (() async {
50
- await test ();
56
+ await test (testNumber);
57
+ });
58
+ final computeExecutionTime = await measureExecutionTime (() async {
59
+ await compute <int , void >(test, testNumber);
51
60
});
52
61
53
62
isTestRunning = false ;
54
63
results.add (
55
64
TestResult (
56
- anotherThreadExecutionTime: anotherThreadExecutionTime,
65
+ computeExecutionTime: computeExecutionTime,
66
+ isolateExecutionTime: isolateExecutionTime,
57
67
mainThreadExecutionTime: mainThreadExecutionTime,
58
68
testType: TestType .createNumbersArray,
59
69
),
@@ -77,7 +87,7 @@ Future<Duration> measureExecutionTime(
77
87
return stopwatch.elapsed;
78
88
}
79
89
80
- Future <void > workInBackground (void Function (SendPort ) test) async {
90
+ Future <void > workInIsolate (void Function (SendPort ) test) async {
81
91
final port = ReceivePort ('test' );
82
92
await Isolate .spawn (test, port.sendPort);
83
93
await port.first;
0 commit comments