CPU load generator

C

choo9292

Hi

I'm trying to make a CPU load generator with c#.
If I set a certain amount of CPU usage like 20%, then it makes CPU to
run at a certain percentage.
Please give me any idea or sample codes.
Thanks.
 
A

Arne Vajhøj

I'm trying to make a CPU load generator with c#.
If I set a certain amount of CPU usage like 20%, then it makes CPU to
run at a certain percentage.

See code below.

Arne

==================================

using System;
using System.Diagnostics;
using System.Threading;

namespace E
{
public class Program
{
private const double LOAD = 0.25;
public static void Main(string[] args)
{
DateTime startwall = DateTime.Now;
double startcpu =
Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
int t = 100;
while(true)
{
double x = 2;
for(int i = 0; i < 1000000; i++)
{
x = Math.Pow(Math.Sqrt(x), 2);
}
DateTime currwall = DateTime.Now;
double deltawall = (currwall -
startwall).TotalMilliseconds;
double currcpu =
Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
double deltacpu = currcpu - startcpu;
double usage = deltacpu / deltawall;
t = (int)(t * usage/LOAD + 0.5);
Thread.Sleep(t);
startwall = currwall;
startcpu = currcpu;
}
}
}
}
 
B

Ben Voigt [C++ MVP]

Arne Vajhøj said:
See code below.

I would use x = 4 or else roundoff error might creep in and slowly change
the value of x, you might ultimately even get an exception after some time
(more likely it will stabilize at some value != 2 that roundtrips).
Arne

==================================

using System;
using System.Diagnostics;
using System.Threading;

namespace E
{
public class Program
{
private const double LOAD = 0.25;
public static void Main(string[] args)
{
DateTime startwall = DateTime.Now;
double startcpu =
Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
int t = 100;
while(true)
{
double x = 2;
for(int i = 0; i < 1000000; i++)
{
x = Math.Pow(Math.Sqrt(x), 2);
}
DateTime currwall = DateTime.Now;
double deltawall = (currwall -
startwall).TotalMilliseconds;
double currcpu =
Process.GetCurrentProcess().TotalProcessorTime.TotalMilliseconds;
double deltacpu = currcpu - startcpu;
double usage = deltacpu / deltawall;
t = (int)(t * usage/LOAD + 0.5);
Thread.Sleep(t);
startwall = currwall;
startcpu = currcpu;
}
}
}
}
 

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

Top