1 /*
2  * Copyright 2018 Oticon A/S
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <time.h>
7 #include <stdint.h>
8 #include "bs_tracing.h"
9 #include "bs_pc_base.h"
10 #include "bs_types.h"
11 #include "bs_time_monitor_args.h"
12 
13 /**
14  * This device monitors the running speed of the simulation
15  */
16 
17 /*
18  * How many waits we will queue before waiting for the first response
19  * Queuing them, reduces the overhead of the monitoring
20  */
21 #define QUEUE_DEPTH 10
22 
23 static pb_dev_state_t pb_dev_state = {0};
24 
clean_up()25 static uint8_t clean_up() {
26   bs_trace_raw(8, "Cleaning up\n");
27   pb_dev_clean_up(&pb_dev_state);
28   return 0;
29 }
30 
main(int argc,char * argv[])31 int main(int argc, char *argv[]) {
32   time_monitor_args_t args;
33 
34   bs_trace_register_cleanup_function(clean_up);
35   bs_time_monitor_argparse(argc, argv, &args);
36 
37   bs_trace_raw(9,"Connecting...\n");
38   pb_dev_init_com(&pb_dev_state, args.device_nbr, args.s_id, args.p_id);
39 
40   bs_time_t time = args.interval;
41   bs_time_t time_r = 0;
42   pb_wait_t wait_s;
43   struct timespec tv;
44 
45   bs_time_t tic_start, tic_end, tic_1st_start;
46   clock_gettime(CLOCK_MONOTONIC, &tv);
47   tic_start = tic_1st_start = tv.tv_sec*1e6 + tv.tv_nsec/1000;
48 
49   for (int i = 0; i < QUEUE_DEPTH - 1; i++) {
50     wait_s.end = time;
51     if (pb_dev_request_wait_nonblock(&pb_dev_state, &wait_s) == -1) {
52       bs_trace_raw(3,"We have been told to disconnect\n");
53       break;
54     }
55     time += args.interval;
56   }
57 
58   while (pb_dev_state.connected){
59     wait_s.end = time;
60     if (pb_dev_request_wait_nonblock(&pb_dev_state, &wait_s) == -1) {
61       bs_trace_raw(3,"We have been told to disconnect\n");
62       break;
63     }
64     if (pb_dev_pick_wait_resp(&pb_dev_state) == -1) {
65       bs_trace_raw(3,"We have been told to disconnect\n");
66       break;
67     }
68     time_r += args.interval;
69 
70     clock_gettime(CLOCK_MONOTONIC, &tv);
71     tic_end = tv.tv_sec*1e6 + tv.tv_nsec/1000;
72 
73     bs_trace_raw_manual_time(2, time_r,
74                              "@%"PRItime"us reached (instantaneous speed=%.2fx, average=%.2fx)        \r",
75                              time_r, args.interval/(double)(tic_end-tic_start), time_r/(double)(tic_end-tic_1st_start));
76     fflush(stdout);
77     time += args.interval;
78     tic_start = tic_end;
79   }
80 
81   bs_trace_raw_manual_time(2, time_r,
82                            "@%"PRItime"us (end) reached (average speed %.2fx)                   \n",
83                            time_r, time_r/(double)(tic_end-tic_1st_start));
84 
85   bs_trace_raw(9,"Disconnecting...\n");
86   pb_dev_disconnect(&pb_dev_state);
87 
88   return 0;
89 }
90