Skip to content

Commit d6c6ffb

Browse files
committed
fix: use monotonic time for throughput example
1 parent e772c64 commit d6c6ffb

File tree

1 file changed

+18
-20
lines changed

1 file changed

+18
-20
lines changed

examples/unix/c11/z_sub_thr.c

+18-20
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,13 @@
1919

2020
#include "zenoh-pico.h"
2121

22-
#define N 1000000
22+
#define PACKET_NB 1000000
2323

2424
typedef struct {
2525
volatile unsigned long count;
2626
volatile unsigned long finished_rounds;
27-
volatile clock_t start;
28-
volatile clock_t stop;
29-
volatile clock_t first_start;
27+
z_clock_t start;
28+
z_clock_t first_start;
3029
} z_stats_t;
3130

3231
#if Z_FEATURE_SUBSCRIPTION == 1
@@ -35,36 +34,35 @@ z_stats_t *z_stats_make(void) {
3534
z_stats_t *stats = malloc(sizeof(z_stats_t));
3635
stats->count = 0;
3736
stats->finished_rounds = 0;
38-
stats->first_start = 0;
37+
stats->first_start.tv_nsec = 0;
3938
return stats;
4039
}
4140

4241
void on_sample(const z_sample_t *sample, void *context) {
4342
(void)sample;
4443
z_stats_t *stats = (z_stats_t *)context;
45-
if (stats->count == 0) {
46-
stats->start = clock();
47-
if (!stats->first_start) {
44+
stats->count++;
45+
// Start set measurement
46+
if (stats->count == 1) {
47+
stats->start = z_clock_now();
48+
if (stats->first_start.tv_nsec == 0) {
4849
stats->first_start = stats->start;
4950
}
50-
stats->count++;
51-
} else if (stats->count < N) {
52-
stats->count++;
53-
} else {
54-
stats->stop = clock();
51+
} else if (stats->count >= PACKET_NB) {
52+
// Stop set measurement
5553
stats->finished_rounds++;
56-
printf("%f msg/s\n", N * (double)CLOCKS_PER_SEC / (double)(stats->stop - stats->start));
54+
unsigned long elapsed_ms = z_clock_elapsed_ms(&stats->start);
55+
printf("Received %d msg in %lu ms (%.1f msg/s)\n", PACKET_NB, elapsed_ms, (double)(PACKET_NB * 1000 / elapsed_ms));
5756
stats->count = 0;
5857
}
5958
}
6059

6160
void drop_stats(void *context) {
62-
const clock_t end = clock();
63-
const z_stats_t *stats = (z_stats_t *)context;
64-
const double elapsed = (double)(end - stats->first_start) / (double)CLOCKS_PER_SEC;
65-
const unsigned long sent_messages = N * stats->finished_rounds + stats->count;
66-
printf("Stats being dropped after unsubscribing: sent %ld messages over %f seconds (%f msg/s)\n", sent_messages,
67-
elapsed, (double)sent_messages / elapsed);
61+
z_stats_t *stats = (z_stats_t *)context;
62+
unsigned long elapsed_ms = z_clock_elapsed_ms(&stats->first_start);
63+
const unsigned long sent_messages = PACKET_NB * stats->finished_rounds + stats->count;
64+
printf("Stats after unsubscribing: received %ld messages over %lu miliseconds (%.1f msg/s)\n", sent_messages,
65+
elapsed_ms, (double)(sent_messages * 1000 / elapsed_ms));
6866
free(context);
6967
}
7068

0 commit comments

Comments
 (0)