Search code examples
bashloopsubuntuffmpegcpu-usage

Limit cpu limit of process in a loop


I am trying to execute ffmpeg in a loop over multiple files. I only want one instance to run at a time, and to only use 50% of the cpu. I've been trying cpulimit but it isn't playing nice with the loop.

for i in {1..9}; do cpulimit -l 50 -- ffmpeg <all the options>; done

This spawns all nine jobs at once, and they are all owned by init so I have to open htop to kill them.

for i in {1..9}; do ffmpeg <all the options> & cpulimit -p $! -l 50; done

This hangs, ctrl+c continues to the next loop iteration. These instances can only be killed by SIGKILL.


Solution

  • Using a queue is the way to go. A simple solution that I use is Task Spooler. You can limit the number of cores ffmpeg uses with -threads also. Here's some code for you:

    ts sh -c "ffmpeg -threads 4 -i INPUT.mp4 -threads 4 OUTPUT.mp4"
    
    • You can set the max number of simultaneous tasks to 1 with: ts -S 1
    • To see the current queue just run ts
    • EDIT: added -threads 4 before -i to limit decoding and encoding CPU usage