simulate high cpu usage for certain period of time
You will need to write a spin loop to keep the processor busy for the amount of time desired. Sleep(n) won't work because while it keeps your thread busy it allows the CPU to do something else.
Use a thread-based timer (not a message based timer) to schedule regular execution of your load simulator function, say, every 10 seconds. In that function, run your spin loop (a for loop that increments a local variable) until the desired load time (% of 10 seconds) is reached, then exit the function. The timer will call you again in (about) 10 seconds to chew up another timeslice. So, for 30% load, your spin loop should churn for 3 seconds out of each 10 second interval.
You should also consider the number of executable cores that are present in your system. On a quad core hyperthreaded Intel processor, you should create 8 threads and run your load simulator in each thread.
Simulating CPU Load In C++
At first sight, this looks like not-pretty-but-correct C++ or C (an easy way to be sure is to compile it). Includes are missing (<windows.h>
, <process.h>
, and <time.h>
) but otherwise it compiles fine.
Note that clock
and Sleep
are not terribly accurate, and Sleep
is not terribly reliable either. On the average, the thread function should kind of work as intended, though (give or take a few percent of variation).
However, regarding question 2) you should replace the last while(1){}
with something that blocks rather than spins (e.g. WaitForSingleObject
or Sleep
if you will). otherwise the entire program will not have 50% load on a quadcore. You will have 100% load on one core due to the main thread, plus the 4x 50% from your four workers. This will obviously sum up to more than 50% per core (and will cause threads to bounce from one core to the other, resulting in nasty side effects).
Using Task Manager or a similar utility to verify whether you get the load you want is a good option (and since it's the easiest solution, it's also the best one).
Also do note that simulating load in such a way will probably kind of work, but is not 100% reliable.
There might be effects (memory, execution units) that are hard to predict. Assume for example that you're using 100% of the CPU's integer execution units with this loop (reasonable assumption) but zero of it's floating point or SSE units. Modern CPUs may share resources between real or logical cores, and you might not be able to predict exactly what effects you get. Or, another thread may be memory bound or having significant page faults, so taking away CPU time won't affect it nearly as much as you think (might in fact give it enough time to make prefetching work better). Or, it might block on AGP transfers. Or, something else you can't tell.
EDIT:
Improved version, shorter code that fixes a few issues and also works as intended:
- Uses
clock_t
for the value returned byclock
(which is technically "more correct" than using a not speciallytypedef
'd integer. Incidentially, that's probably the very reason why the original code does not work as intended, sinceclock_t
is a signed integer under Win32. The condition inif()
always evaluatestrue
, so the workers sleep almost all the time, consuming no CPU. - Less code, less complicated math when spinning. Computes a wakeup time 50 ticks in the future and spins until that time is reached.
- Uses
getchar
to block the program at the end. This does not burn CPU time, and it allows you to end the program by pressing Enter. Threads are not properly ended as one would normally do, but in this simple case it's probably OK to just let the OS terminate them as the process exits. - Like the original code, this assumes that
clock
andSleep
use the same ticks. That is admittedly a bold assumption, but it holds true under Win32 which you used in the original code (both "ticks" are milliseconds). C++ doesn't have anything likeSleep
(withoutboost::thread
, or C++11std::thread
), so if non-Windows portability is intended, you'd have to rethink anyway. - Like the original code, it relies on functions (
clock
andSleep
) which are unprecise and unreliable.Sleep(50)
equalsSleep(63)
on my system without usingtimeBeginPeriod
. Nevertheless, the program works "almost perfectly", resulting in a 50% +/- 0.5% load on my machine. Like the original code, this does not take thread priorities into account. A process that has a higher than normal priority class will be entirely unimpressed by this throttling code, because that is how the Windows scheduler works.
#include <windows.h>
#include <process.h>
#include <time.h>
#include <stdio.h>
void task1(void *)
{
while(1)
{
clock_t wakeup = clock() + 50;
while(clock() < wakeup) {}
Sleep(50);
}
}
int main(int, char**)
{
int ThreadNr;
for(int i=0; i < 4; i++) _beginthread( task1, 0, &ThreadNr );
(void) getchar();
return 0;
}
Easiest way to simulate the maximum CPU load?
Your code is serial. You have eight available threads (4 cores * 2 threads per core = 8 total threads), and your current code uses one of them for 1 thread / 8 available = 12.5%
of your CPU. If you have to write your own code (and not use a pre-existing intensive code as already suggested by others), I would recommend putting a #pragma omp parallel
above your while
loop and compiling with the -fopenmp
flag (assuming you are using MinGW, if not, the exact option may vary) so that you use all of the available threads instead.
How to to force a process to have high CPU
If you are using multi core processor Use ThreadPool to spam threads. spam as number of processor should be enough to make cpu almost 100% load.
private static void Main()
{
for (int i = 0; i < Environment.ProcessorCount; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
}
Console.ReadLine();
}
static void ThreadProc(Object stateInfo)
{
while (true)
{
// do something
}
}
How To Simulate Lower CPU Processor Machines For Browser Testing
Most new CPUs multiplier can easily be lowered (Intel: Speedstep, AMD: PowerNow!). This is used to save power. With RMclock you can manually adjust your multiplier and thus lower your frequency and make your pc slower. I use this tool myself so I can tell you that it works.
http://cpu.rightmark.org/products/rmclock.shtml
Related Topics
Is There Any JSON Web Token (Jwt) Example in C#
Convert from Scientific Notation String to Float in C#
An Object Reference Is Required for the Non-Static Field, Method, or Property
When a Class Is Inherited from List<>, Xmlserializer Doesn't Serialize Other Attributes
Replace Unicode Escape Sequences in a String
Resharper Warning - Access to Modified Closure
Extremely Large Single-Line File Parse
Creating Diagonal Pattern in Wpf
What Is the Best Practice for "Copy Local" and with Project References
Why Must We Define Both == and != in C#
C# Split String and Remove Empty String
Gmail Smtp via C# .Net Errors on All Ports