Jatin Kumar
Jatin Kumar

Reputation: 2785

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 ?

Upvotes: 5

Views: 209

Answers (2)

cnicutar
cnicutar

Reputation: 182619

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.

Upvotes: 6

user541686
user541686

Reputation: 210352

Not platform-independently, but in Windows, you can use SetProcessAffinityMask:

SetProcessAffinityMask(GetCurrentProcess(), 0x1); //Only CPU #1

Upvotes: 6

Related Questions