Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit No. of CPU in C

I was testing a c code on a physical and virtual machine and i need to limit the no. of cpu used during execution of c program. Is there a way to do this ?

like image 466
Jatin Kumar Avatar asked May 21 '11 07:05

Jatin Kumar


People also ask

Which system call can be used to limit the amount of CPU time a process can use?

There are at least three ways in which you can control how much CPU time a process gets: Use the nice command to manually lower the task's priority. Use the cpulimit command to repeatedly pause the process so that it doesn't exceed a certain limit.


1 Answers

For Linux there is sched_setaffinity. For instance if you want it to run just on CPUs 1 and 3:

cpu_set_t set;

CPU_ZERO(&set);
CPU_SET(1, &set);
CPU_SET(3, &set);

sched_setaffinity(pid, CPU_SETSIZE, &set);

Caution: sched_setaffinity and sched_getaffinity are Linux-specific (they don't exist on other POSIX systems).

On BSDs there is cpuset_setaffinity with similar semantics. I expect Solaris to have a similar feature.

like image 188
cnicutar Avatar answered Sep 26 '22 01:09

cnicutar