Question of throttling CPU usage

J

jon.harding

Hi, can someone help with how I can throttle CPU usage in a c
application.

By means of an example, in this trivial application

int main(int argc, char *argv[]) {
int i;
while (1) {
i++;
}
}


how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

Thank you
Jon
 
J

James Kuyper

Hi, can someone help with how I can throttle CPU usage in a c
application.

By means of an example, in this trivial application

int main(int argc, char *argv[]) {
int i;
while (1) {
i++;
}
}


how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.

For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.
 
J

jon.harding

Hi, can someone help with how I can throttle CPU usage in a c
application.
By means of an example, in this trivial application
int main(int argc, char *argv[]) {
    int i;
    while (1) {
       i++;
     }
}
how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.

For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.

Thank you James.

I was thinking of doing something like your suggestion but my
application will hopefully run on both Windows and Linux so I won't be
able to set process priority or the nice factor.

Where I got my idea from is from boinc. In boinc you can set the CPU
usage to be anything from 1-100, and even configure the program to
suspend itself when the computer is doing something else, so that is
using idle time and not being antisocial to whatever else the computer
is doing. I am thinking of something like this. Maybe as you suggest,
I will just check the time every now and then and for 20% usage, I
will just run at 100% CPU for short bursts, work out how much time it
took to do the burst, and then do nothing for 8 * that time, and
repeat.
Jon
 
T

Thomas Richter

Where I got my idea from is from boinc. In boinc you can set the CPU
usage to be anything from 1-100, and even configure the program to
suspend itself when the computer is doing something else, so that is
using idle time and not being antisocial to whatever else the computer
is doing. I am thinking of something like this. Maybe as you suggest,
I will just check the time every now and then and for 20% usage, I
will just run at 100% CPU for short bursts, work out how much time it
took to do the burst, and then do nothing for 8 * that time, and
repeat.

But there we have exactly the problem: There is no portable way of
"doing nothing" in C. You somehow need to use the operating system for
that, or any other library outside of the C standard.

Greetings,
Thomas
 
L

Lanarcam

Le 25/04/2012 20:44, James Kuyper a écrit :
Hi, can someone help with how I can throttle CPU usage in a c
application.

By means of an example, in this trivial application

int main(int argc, char *argv[]) {
int i;
while (1) {
i++;
}
}


how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.

For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.

This is not only system dependant but also processor dependant. For
instance Cortex M0 processor have instructions for entering sleep
mode.

"Wait for interrupt

The Wait For Interrupt instruction, WFI, causes immediate entry
to sleep mode. When the processor executes a WFI instruction it
stops executing instructions and enters sleep mode. See WFI for
more information.

Wait for event

The Wait For Event instruction, WFE, causes entry to sleep
mode conditional on the value of a one-bit event register.
When the processor executes a WFE instruction, it checks
the value of the event register:

0

The processor stops executing instructions and enters sleep
mode

1

The processor sets the register to zero and continues
executing instructions without entering sleep mode."

Obviously, the OS or RTOS must support those instructions.

<http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0497a/BABHHGEB.html>
 
J

James Kuyper

Hi, can someone help with how I can throttle CPU usage in a c
application.
By means of an example, in this trivial application
int main(int argc, char *argv[]) {
int i;
while (1) {
i++;
}
}
how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.

For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.

Thank you James.

I was thinking of doing something like your suggestion but my
application will hopefully run on both Windows and Linux so I won't be
able to set process priority or the nice factor.

Where I got my idea from is from boinc. In boinc you can set the CPU
usage to be anything from 1-100, and even configure the program to
suspend itself when the computer is doing something else, so that is
using idle time and not being antisocial to whatever else the computer
is doing. I am thinking of something like this. Maybe as you suggest,
I will just check the time every now and then and for 20% usage, I
will just run at 100% CPU for short bursts, work out how much time it
took to do the burst, and then do nothing for 8 * that time, and
repeat.

The tricky part of that is "do nothing". The C standard doesn't provide
any mechanism for doing that; you'll have to find a method specific to
your operating system for doing it. That's what sleep() is for;
presumably there's a Windows equivalent - it might even be called
sleep(), for all I know.

In your example:

int i;
while(1) {
i++;
}

This code has undefined behavior for two separate reasons. First of all,
'i' is uninitialized; that means that it could, among other
possibilities, have a trap representation. Any attempt to read the value
of an object containing a trap representation has undefined behavior. On
a system where 'int' has no trap representations, which is most
real-world systems, that's probably not a problem, but you should get in
the habit of always initializing every variable sometime before the
first time that its value is read.

The second reason is that your program keeps incrementing 'i' until it
reaches INT_MAX, and then executes i++ one more time. As soon as it does
that, the behavior is undefined. In fact, as soon as it becomes
inevitable that this will happen (which is the moment your program
starts) the behavior is undefined. Again, on many systems this will do
something innocuous, such as set i to INT_MIN, but there's no guarantees
that the result will be that painless. You can avoid both problems by using

unsigned u = 0;
while(1) {
u++;
}

The behavior of u++ when u is UINT_MAX is well-defined; it sets u to 0.

Because your code makes no use of the value of i after the end of the
loop, a good optimizing compiler can convert your code into the
equivalent of:

int main(void) { while(1); }

It's been argued that a really good optimizing compiler can execute an
infinite empty loop in a finite amount of time, since infinity*0 has no
well defined meaning. The mathematical part of that argument is suspect,
but the C standard never specifies anything about how long your program
should take to execute, so it is arguably the case that such a compiler
could implement your program as the equivalent of

int main(void) { }

That's pretty much just a joke, but the underlying truth behind that
joke is that with modern optimizing compilers, the only way to make sure
that your loop actually wastes time doing something, is to make sure
that the thing it does can't be optimized away.

Getting back to my main point: if the thing your loop is doing can't be
optimized away, then it doesn't qualify as "do nothing".
 
J

jon.harding

On 04/25/2012 02:22 PM, (e-mail address removed) wrote:
Hi, can someone help with how I can throttle CPU usage in a c
application.
By means of an example, in this trivial application
int main(int argc, char *argv[]) {
    int i;
    while (1) {
       i++;
     }
}
how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.
The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.
For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.
Thank you James.
I was thinking of doing something like your suggestion but my
application will hopefully run on both Windows and Linux so I won't be
able to set process priority or the nice factor.
Where I got my idea from is from boinc. In boinc you can set the CPU
usage to be anything from 1-100, and even configure the program to
suspend itself when the computer is doing something else, so that is
using idle time and not being antisocial to whatever else the computer
is doing. I am thinking of something like this. Maybe as you suggest,
I will just check the time every now and then and for 20% usage, I
will just run at 100% CPU for short bursts, work out how much time it
took to do the burst, and then do nothing for 8 * that time, and
repeat.

The tricky part of that is "do nothing". The C standard doesn't provide
any mechanism for doing that; you'll have to find  a method specific to
your operating system for doing it. That's what sleep() is for;
presumably there's a Windows equivalent - it might even be called
sleep(), for all I know.

In your example:

        int i;
        while(1) {
            i++;
        }

This code has undefined behavior for two separate reasons. First of all,
'i' is uninitialized; that means that it could, among other
possibilities, have a trap representation. Any attempt to read the value
of an object containing a trap representation has undefined behavior. On
a system where 'int' has no trap representations, which is most
real-world systems, that's probably not a problem, but you should get in
the habit of always initializing every variable sometime before the
first time that its value is read.

The second reason is that your program keeps incrementing 'i' until it
reaches INT_MAX, and then executes i++ one more time. As soon as it does
that, the behavior is undefined. In fact, as soon as it becomes
inevitable that this will happen (which is the moment your program
starts) the behavior is undefined. Again, on many systems this will do
something innocuous, such as set i to INT_MIN, but there's no guarantees
that the result will be that painless. You can avoid both problems by using

        unsigned u = 0;
        while(1) {
            u++;
        }

The behavior of u++ when u is UINT_MAX is well-defined; it sets u to 0.

Because your code makes no use of the value of i after the end of the
loop, a good optimizing compiler can convert your code into the
equivalent of:

        int main(void) { while(1); }

It's been argued that a really good optimizing compiler can execute an
infinite empty loop in a finite amount of time, since infinity*0 has no
well defined meaning. The mathematical part of that argument is suspect,
but the C standard never specifies anything about how long your program
should take to execute, so it is arguably the case that such a compiler
could implement your program as the equivalent of

        int main(void) { }

That's pretty much just a joke, but the underlying truth behind that
joke is that with modern optimizing compilers, the only way to make sure
that your loop actually wastes time doing something, is to make sure
that the thing it does can't be optimized away.

Getting back to my main point: if the thing your loop is doing can't be
optimized away, then it doesn't qualify as "do nothing".

OK, I understand. I am new to c.

Let me put it this way, can I do what I want in c++? I don't know that
language either, but I may as well learn the one that will let me do
what I want.
Thank you again
James
 
I

Ian Collins

OK, I understand. I am new to c.

Let me put it this way, can I do what I want in c++? I don't know that
language either, but I may as well learn the one that will let me do
what I want.

No. The same conditions apply.

If you want to manage CPU utilisation, it has to be done either outside
of the application, or in a system dependent way.
 
J

jon.harding

No.  The same conditions apply.

If you want to manage CPU utilisation, it has to be done either outside
of the application, or in a system dependent way.

OK, and I am sorry to labour the point here, but how can I do this
outside the application then?

Here are the requirements:
1. My program will run hopefully on Windows and Linux.
2. My program should run at a set CPU percentage and not exceed it.
3. The CPU percentage may be different depending on the time of day;
ie after 6pm and over a lunch break 12:30 - 1:00pm it will run at 85%
utilization, but at other times around 10%

Ideally something from sourceforge would be ideal to wrap my
application but I cannot find anything.
Thank you
Jon
 
J

James Kuyper

OK, and I am sorry to labour the point here, but how can I do this
outside the application then?

I think "system dependent" rather than "outside the application" is your
best bet, given the following requirements.
Here are the requirements:
1. My program will run hopefully on Windows and Linux.
2. My program should run at a set CPU percentage and not exceed it.
3. The CPU percentage may be different depending on the time of day;
ie after 6pm and over a lunch break 12:30 - 1:00pm it will run at 85%
utilization, but at other times around 10%

For the Linux side, we've already discussed how clock() and sleep()
could be used to manage your CPU percentage. localtime() provides the
mechanism for making the % vary with time of day.

For Windows, I can't help you - I haven't had to program for that
environment in nearly two decades. But Robert Wessel seems to have dealt
with that side.
 
N

Nobody

The tricky part of that is "do nothing". The C standard doesn't provide
any mechanism for doing that; you'll have to find a method specific to
your operating system for doing it. That's what sleep() is for;
presumably there's a Windows equivalent - it might even be called
sleep(), for all I know.

Actually, it's called Sleep() (with an upper-case S); the argument is in
milliseconds (as opposed to seconds for the Unix version).
 
N

Nobody

OK, and I am sorry to labour the point here, but how can I do this
outside the application then?

Here are the requirements:
1. My program will run hopefully on Windows and Linux.
2. My program should run at a set CPU percentage and not exceed it.
3. The CPU percentage may be different depending on the time of day;
ie after 6pm and over a lunch break 12:30 - 1:00pm it will run at 85%
utilization, but at other times around 10%

You'll probably have to do it within the application, using
platform-specific functionality (e.g. sleep, usleep or nanosleep on Unix,
Sleep on Windows).

Very few real programs can be written using only the functionality
provided by the library. E.g. almost all file handling is
platform-specific: even with <stdio.h>, the standard doesn't specify which
filenames are valid, and the standard makes no mention of directories.
 
F

Fred K

You'll probably have to do it within the application, using
platform-specific functionality (e.g. sleep, usleep or nanosleep on Unix,
Sleep on Windows).

Very few real programs can be written using only the functionality
provided by the library. E.g. almost all file handling is
platform-specific: even with <stdio.h>, the standard doesn't specify which
filenames are valid, and the standard makes no mention of directories.

Regardless of what you use to try slowing the program down, you probably can't cause it to use a specific amount of the CPU time. There are likely to be many other things running at the same time that you have no control over, and they will share CPU time with your progam.

Suppose you specify your program to use 85% of the CPU time. Now run two instances of your program at the same time. Do you really expect each of themto use 85% of the CPU time?
 
J

James Kuyper

....
Regardless of what you use to try slowing the program down, you probably can't cause it to use a specific amount of the CPU time. There are likely to be many other things running at the same time that you have no control over, and they will share CPU time with your progam.

Suppose you specify your program to use 85% of the CPU time. Now run two instances of your program at the same time. Do you really expect each of them to use 85% of the CPU time?

It's feasible to mandate that your program must use no more than X% of
the CPU time, while allowing for the possibility of using less than X%.
It's possible to interpret jon.harding's specification above as implying
that: he emphasizes that CPU usage must "not exceed" the specified
percentage.
 
T

tom st denis

On 04/25/2012 02:22 PM, (e-mail address removed) wrote:
Hi, can someone help with how I can throttle CPU usage in a c
application.
By means of an example, in this trivial application
int main(int argc, char *argv[]) {
    int i;
    while (1) {
       i++;
     }
}
how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.
The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.
For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.

Thank you James.

I was thinking of doing something like your suggestion but my
application will hopefully run on both Windows and Linux so I won't be
able to set process priority or the nice factor.

You can create threads with various priority settings in Windows. And
you can use nice() in Linux/UNIX.... Both can then call a standard
library function you write to process "work."

All of which is OT...

BTW typically if someone wants to run a daemon that does background
heat generation [er... number crunching for whatever cause] they don't
want it fixed to a max of x% but more so "lowest damn priority
possible."

As per your later posts I don't get what a "upto x%" limit buys you.
Why not just set x to 100 and then run it at idle level? Would
someone really want their computer to be 50% idling when not doing
anything giving your program 50% of the cpu? In terms of energy
efficiency it's actually better to give it 100% (for instance, the
higher power draw of the ARM A15 than the A9 is offset by the fact the
core is busy less doing the same unit of work).

Tom
 
R

Robert Miles

Hi, can someone help with how I can throttle CPU usage in a c
application.
By means of an example, in this trivial application
int main(int argc, char *argv[]) {
int i;
while (1) {
i++;
}
}
how can I limit the CPU usage for the loop to be 10% or 20% or 50% or
whatever integer I pass in on the command line.

The C standard provides no mechanism for doing this; whether there is
any such mechanism, and how to use it, will depend upon your operating
system.

For instance, on unix-like systems:
sleep() provides a mechanism for relinquishing control of the CPU for a
period of time; To achieve a desired percentage of the time, use calls
to clock() to determine when the next time should be for a call to sleep().
If all you really want is to reduce your CPU usage, without needing
precise control over reduction, call the nice() function to lower the
scheduling priority for your process.

Thank you James.

I was thinking of doing something like your suggestion but my
application will hopefully run on both Windows and Linux so I won't be
able to set process priority or the nice factor.

Where I got my idea from is from boinc. In boinc you can set the CPU
usage to be anything from 1-100, and even configure the program to
suspend itself when the computer is doing something else, so that is
using idle time and not being antisocial to whatever else the computer
is doing. I am thinking of something like this. Maybe as you suggest,
I will just check the time every now and then and for 20% usage, I
will just run at 100% CPU for short bursts, work out how much time it
took to do the burst, and then do nothing for 8 * that time, and
repeat.
Jon

There's a BOINC add-on called Throttle which provides the function
you want, for Windows. The documentation says it can be applied to
non-BOINC programs, but doesn't make it very clear how.

http://efmer.eu/boinc/

I haven't found whether it was written in C.
 
R

Robert Miles

I think "system dependent" rather than "outside the application" is your
best bet, given the following requirements.


For the Linux side, we've already discussed how clock() and sleep()
could be used to manage your CPU percentage. localtime() provides the
mechanism for making the % vary with time of day.

For Windows, I can't help you - I haven't had to program for that
environment in nearly two decades. But Robert Wessel seems to have dealt
with that side.

I've used the Cygwin Linux-emulation under Windows, and it provides
clock(), sleep(), and localtime(). Use the info command for locating
details on how to call each of them.

Robert Miles
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top