简体   繁体   中英

python program slower running as a systemd than running it from terminal

I have raspberri pi zero WH which has just 1 Core .

I have a program that runs in a loop, listens to incoming UDP packets and process them. It is crucial for me, that the packets and further logic is processed in 0.025s (to be more clear, there is eternal loop(even if no packets are coming) and whatever happens, the loop cannot exceed 0.025s).

I am fairly succesful with this if I run my program from terminal as

sudo python3 script.py

However, if I run it with systemd as a service , it seems that the program is not taking enough resources. Loops are failing the 0.025s condition. Also it seems from htop, that running my program as a service makes one thread less (I cant guarantee this fact, just quick observation).

I dont have experience with systemd services , so maybe the problem is with my configuration

[Unit]
Description=App

[Service]
ExecStart=sudo /usr/bin/python3 /home/pi/script.py
WorkingDirectory=/home/pi/
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

My question is, is this standard behaviour or systemd service should behave same as program runned from terminal?

It is entirely possible that scripts running as systemd service may be slower than directly from Terminal - likely due to different resource allocations. For instance, I would expect scripts ran from Terminal (ie explicitly by the user) to receive a higher priority and therefore greater amount of resources in contrast to background processing.

You can, however, assign more resources including CPU and RAM to your service using systemd.resource-control .

For example, you could try increasing CPUWeight from the default value of 100 to 1,000.

[Service]
CPUWeight = 1000

Adjusting other parameters may finally lead to your desired execution time. Do keep in mind that providing a greater amount of resources to your service it may impact the performance of your overall system.

I had a similar issue and solved this by creating a "user.service". Save the unit file in:

/home/$USER/.config/system/user/<xyz>.service

then start it via:

systemctl --user start xyz

The performance is then the same as if you were running it via a logged in shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM