forked from shamblett/coap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_vs_async.dart
64 lines (52 loc) · 1.53 KB
/
sync_vs_async.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// ignore_for_file: avoid_print
/*
* Package : Coap
* Author : S. Hamblett <[email protected]>
* Date : 06/06/2018
* Copyright : S.Hamblett
*
* Asynchronous vs synchronous benchmark
*/
import 'dart:async';
import 'package:coap/coap.dart';
import 'config/coap_config.dart';
FutureOr<void> main() async {
final conf = CoapConfig();
final baseUri = Uri(
scheme: 'coap',
host: 'californium.eclipseprojects.io',
port: conf.defaultPort,
);
final client = CoapClient(baseUri, config: conf);
try {
// Warm up (create socket etc.)
await client.get(Uri(path: 'test'));
final stopwatch = Stopwatch()..start();
print('Sending 10 async requests...');
final futures = <Future<void>>[];
for (var i = 0; i < 10; i++) {
futures.add(
client.get(Uri(path: 'test')).then((final resp) {
if (resp.responseCode != ResponseCode.content) {
print('Request failed!');
}
}),
);
}
// Wait until all requests are done
await Future.wait(futures);
print('10 async requests took ${stopwatch.elapsedMilliseconds} ms');
stopwatch.reset();
print('Sending 10 sync requests...');
for (var i = 0; i < 10; i++) {
final resp = await client.get(Uri(path: 'test'));
if (resp.responseCode != ResponseCode.content) {
print('Request failed!');
}
}
print('10 sync requests took ${stopwatch.elapsedMilliseconds} ms');
} on Exception catch (e) {
print('CoAP encountered an exception: $e');
}
client.close();
}