Rambo partyush
Rambo partyush

Reputation: 83

Test this UDP socket Python Code: Weird delay; Windows vs Linux

I am sending data with 1ms gap, but at the receiving end, it seems I am getting 15-16 packets at once and then after 15-16 ms delay receiving another set of packets.

Kindly try this code and see if you are having the same results. I am using a Windows 10 machine. I have tried it in 2 pcs with the same result. Any insight would be greatly appreciated.

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  3 23:32:44 2020

@author: Pratyush
"""

# sender.py
import socket
from time import sleep,monotonic_ns

TEMPO = 1e6
send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
last_second = monotonic_ns()
iteration_count = 0
while iteration_count < 1000:
    if monotonic_ns() >= last_second + TEMPO:
        last_second += TEMPO
        send.sendto(bytes(32), ('127.0.0.1', 8208))       
        iteration_count += 1

The receiver code is as follows, run the receiver.py first

# -*- coding: utf-8 -*-
"""
Created on Thu Sep  3 23:32:13 2020

@author: Pratyush
"""

# receiver2.py
import socket
import time
"""
just get the raw values from UDP socket every 1ms
The sender sends it with that temporal resolution

"""

UDP_IP = ""
UDP_PORT = 8208 #UDP phasor values 32 bytes (V,phi,P)
sock_ph = socket.socket(socket.AF_INET,  # Internet
                     socket.SOCK_DGRAM)  # UDP
sock_ph.bind((UDP_IP, UDP_PORT))
print("socket bound, waiting for data...")

while True:
    time_before_raw = time.monotonic_ns()
    raw = sock_ph.recv(32) #I am receiving 32 bytes data
    time_after_raw = time.monotonic_ns()
    # print((time_after_raw-time_before_raw),raw,len(raw))
    print((time_after_raw-time_before_raw),len(raw))

The results I have received are as follows:

0 32
0 32
16000000 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
15000000 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32
0 32

Upvotes: 0

Views: 178

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73051

According to the PEP, Windows’ monotonic clock has a resolution of 15mS. Most likely it is that granularity that you are seeing in your output.

https://www.python.org/dev/peps/pep-0564/#id23

Upvotes: 2

Related Questions