Search code examples
cgroups

Limit total CPU usage with cgroups


I have a script which uses ulimit -t 5 to limit a program to 5 seconds of CPU time.

That program now spawns children, so I want to use cgroups instead, so I can limit the CPU taken by the process, and it's children. However, I can't find a way of placing a hard upper limit on a cgroup's CPU usage.


Solution

  • Cgroups won't kill the process for you, but it will limit its runtime per specific period. You can use a very long period for cpu.cfs_period_us and check the cgroup task list after that period. If the tasks are still running, then kill them manually using:

    kill -9 $(cat /sys/fs/cgroup/.../tasks)

    cpu.cfs_period_us

    specifies a period of time in microseconds (µs, represented here as "us") for how regularly a cgroup's access to CPU resources should be reallocated. If tasks in a cgroup should be able to access a single CPU for 0.2 seconds out of every 1 second, set cpu.cfs_quota_us to 200000 and cpu.cfs_period_us to 1000000. The upper limit of the cpu.cfs_quota_us parameter is 1 second and the lower limit is 1000 microseconds.

    cpu.cfs_quota_us

    specifies the total amount of time in microseconds (µs, represented here as "us") for which all tasks in a cgroup can run during one period (as defined by cpu.cfs_period_us). As soon as tasks in a cgroup use up all the time specified by the quota, they are throttled for the remainder of the time specified by the period and not allowed to run until the next period. If tasks in a cgroup should be able to access a single CPU for 0.2 seconds out of every 1 second, set cpu.cfs_quota_us to 200000 and cpu.cfs_period_us to 1000000. Note that the quota and period parameters operate on a CPU basis. To allow a process to fully utilize two CPUs, for example, set cpu.cfs_quota_us to 200000 and cpu.cfs_period_us to 100000. Setting the value in cpu.cfs_quota_us to -1 indicates that the cgroup does not adhere to any CPU time restrictions. This is also the default value for every cgroup (except the root cgroup).