Reputation: 21
I'm new to python and trying to get some help here. I've written a code to transmit UDP data through the socket. I wanted to re-transmit the data in a loop every 50 microsecond but I can only send it every 3 seconds! I'm sure I'm doing something wrong , can you help me out ? I've pasted the code below:
import socket,codecs,binascii,re ,sched, time
UDP_IP = "XXX.XXX.XXX.XXX"
UDP_PORT = 30001
MESSAGE = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\
x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20'# !"#$%' #"\x00\x01\x02 "
s = sched.scheduler(time.time, time.sleep)
def send_data(sc):
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
print""
print""
print""
print""
print""
sc.enter(0.000050, 1, send_data, (sc,))
print time.time()
print""
print""
s.enter(0.0000050, 1, send_data, (s,))
s.run()
Upvotes: 2
Views: 222
Reputation: 6226
First of all, creating a new socket every time you send data will create quite some overhead. Scheduling a new task over and over adds a lot of overhead as well, slowing your program down even further. The print command can add a little overhead especially if you output a lot of data.
Other things to consider include the precision of the system timers involved, interacting with the hardware, that python is an interpreted language, etc but they are all minor in comparison so you can ignore that. If you wanted to write something real-time critical, C would be a better choice.
So anyway, to speed up your program i would get rid of the time consuming parts:
import socket, time
# ...
def send_data():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True: #TODO: would require an abort condition
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
time.sleep(0.00005) # don't count on this to be 100% accurate
You can put that into a thread if you don't want your main program to block:
from threading import Thread
t = Thread(target=send_data)
t.start()
Upvotes: 1