@@ -53,6 +53,8 @@ int msg_count = 0;
5353struct mosquitto * g_mosq = NULL ;
5454static bool timed_out = false;
5555static int connack_result = 0 ;
56+ static struct timespec publish_send_time ;
57+ static struct timespec publish_recv_time ;
5658
5759#ifndef WIN32
5860static void my_signal_handler (int signum )
@@ -68,6 +70,8 @@ static void my_signal_handler(int signum)
6870
6971int my_publish (struct mosquitto * mosq , int * mid , const char * topic , int payloadlen , void * payload , int qos , bool retain )
7072{
73+ mosquitto_time_ns (& publish_send_time .tv_sec , & publish_send_time .tv_nsec );
74+
7175 if (cfg .protocol_version < MQTT_PROTOCOL_V5 ){
7276 return mosquitto_publish_v5 (mosq , mid , topic , payloadlen , payload , qos , retain , NULL );
7377 }else {
@@ -85,6 +89,8 @@ static void my_message_callback(struct mosquitto *mosq, void *obj, const struct
8589 if (process_messages == false) return ;
8690 if (message -> retain && cfg .no_retain ) return ;
8791
92+ mosquitto_time_ns (& publish_recv_time .tv_sec , & publish_recv_time .tv_nsec );
93+
8894 print_message (& cfg , message , properties );
8995
9096 switch (cfg .pub_mode ){
@@ -267,6 +273,33 @@ static void print_usage(void)
267273 printf ("\nSee https://mosquitto.org/ for more information.\n\n" );
268274}
269275
276+ static void report_latency (void )
277+ {
278+ if (cfg .measure_latency ){
279+ time_t s = publish_recv_time .tv_sec - publish_send_time .tv_sec ;
280+ long ns = publish_recv_time .tv_nsec - publish_send_time .tv_nsec ;
281+
282+ if (s < 0 ){
283+ if (ns < 0 ){
284+ s ++ ;
285+ ns -= 1000000000 ;
286+ }
287+ }
288+
289+ if (s > 0 ){
290+ printf ("Latency: %ld.%09ld\n" , s , ns );
291+ }else {
292+ if (ns < 1000 ){
293+ printf ("Latency: %ldns\n" , ns );
294+ }else if (ns < 1000000 ){
295+ printf ("Latency: %fµs\n" , ((double )ns )/1000.0 );
296+ }else {
297+ printf ("Latency: %fms\n" , ((double )ns )/1000000.0 );
298+ }
299+ }
300+ }
301+ }
302+
270303int main (int argc , char * argv [])
271304{
272305 int rc ;
@@ -385,6 +418,8 @@ int main(int argc, char *argv[])
385418 }
386419 }while (rc == MOSQ_ERR_SUCCESS && client_state != rr_s_disconnect );
387420
421+ report_latency ();
422+
388423 mosquitto_destroy (g_mosq );
389424 mosquitto_lib_cleanup ();
390425
0 commit comments