3

Is there a way to limit CPU usage in C++?

I mean can I write a program which takes input %CPU to be used and it uses maximum that much amount of CPU.

I basically want to add the functionality of cpulimit command internally in the program.

If there is, how to do it ?

Edits:

Environment: Linux (debian) with gcc 6.1. It should support as many arbitrary numbers as possible. i.e a range of 1% - 100% . If the OS cannot do, an error can be logged and the nearest value to it can be used or any other solution that is recommended when the OS restricts that number.

7
  • 2
    To answer the question asked: yes, there is a way to do that. Commented Sep 17, 2016 at 14:41
  • @SamVarshavchik I guess now that I have edited the question, you can help me with telling how can I possibly achieve this ? Commented Sep 17, 2016 at 14:43
  • What operating system? Commented Sep 17, 2016 at 14:43
  • @RaymondChen Linux with gcc Commented Sep 17, 2016 at 14:44
  • @KrisVandermotten I have changed the question to add details about the operating system. Commented Sep 17, 2016 at 14:46

2 Answers 2

2

Use getrusage(), see Linux commands to detect the computer resource usage of a program

And when you check, and you've used however many milliseconds of runtime you want, use nanosleep() to sleep a few milliseconds. Adjust percentages to match your requirements.

Sign up to request clarification or add additional context in comments.

1 Comment

It makes sense, now that linux kernel doesn't provide any such feature. I can do such things.
2

Linux does not provide the means to set a specific percentage. However, the nice(2) system call lowers the priority of the process in relation to other processes on the system, thus achieving some sort of a relative percentage of CPU, in relation to other processes on the system.

You can also use the setrlimit(2) system call to set your process's RLIMIT_CPU, as a fixed amount.

4 Comments

That's a limit in seconds, not percentage.
RLIMIT_CPU only provides limit in time, I more of want to control CPU% which is displayed for every process in top.
But then how does cpulimit work if linux doesn't provide any such functionality? cpulimit command seems to do a fair job in limiting the %CPU usage of a process.
Since the source code to cpulimit is freely available, you can look at it yourself and find out. I just took a brief glance myself, and it is a heuristic algorithm that manually halts and resumes each process using SIGSTOP and SIGCONT. This is not a Linux kernel feature, but a heuristic rate-limiting implementation. You could do the same thing by periodically checking /proc, see how much CPU time your process has burned, then manually sleep() for the same period of time, in order to have a target 50% CPU utilization, for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.