Reputation: 113
I am new to python and am trying to code my own syslog program. I have tested this on my own machine, and it works fine, I don't notice anything. Now when I put it on my Ubuntu VM it spikes the CPU (reported by 'top' and vSphere) to 80-99%. I have allocated 1 CPU core from my i5 (3.1 GHz) processor. If anything, maybe the file opening and closing is causing this spike, but that just doesn't add up to me. Thanks in advance for any help!
import socket
log= input("Enter full path of file you would like to monitor:\n")
host =input("Enter IP address for remote syslog server:\n")
port =input("Enter syslog service port to send syslogs to:\n")
port=int(port)
with open(log,'r') as file:
current_pos = 0
data=file.read().splitlines()
old_len=0
file.close()
while True:
new_len=len(data)
udp_port = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
with open(log,'r') as file:
data=file.read().splitlines()
while new_len > old_len and current_pos < new_len:
msg=data[current_pos]
print('Sending....',msg,'=====>',host,':',port)
udp_port.sendto(bytes(msg, "utf-8"), (host, port))
current_pos+=1
file.close()#Is this necessary here?
old_len=new_len
#udp_port.shutdown()#stay open only during transmission
udp_port.close()
Upvotes: 0
Views: 91
Reputation: 7700
Your code has a while True:
block. This means it is going to loop over and over again, continually reading from your file. The only break the CPU gets is from blocking calls (such as network and other I/O) where your thread will yield CPU time until the I/O resources become available.
To avoid thrashing the CPU, you should put a sleep()
call in at the end of your while
loop. Even a sleep of 10ms should give you low latency, but ease up on the CPU.
Upvotes: 1