Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit CPU Usage in C++

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.

like image 649
BEC Avatar asked Aug 11 '26 16:08

BEC


1 Answers

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.

like image 84
Zan Lynx Avatar answered Aug 14 '26 16:08

Zan Lynx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!