Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Create CPU Usage at Custom Percentage

I'm looking to test system responsiveness etc. on a few machines under certain CPU usage conditions. Unfortunately I can only create ~100% usage (infinite loop) or not enough CPU usage (I'm using C#).

Is there any way, in rough approximation, as other tasks are running on the system as well, to create CPU usage artificially at 20, 30, 40% (and so forth) steps?

I understand that there are differences between systems, obviously, as CPU's vary. It's more about algorithms/ideas on customizable CPU intensive calculations that create enough usage on a current CPU without maxing it out that I can tweak them then in some way to adjust them to create the desired percentage.

like image 434
Alex Avatar asked Aug 22 '09 10:08

Alex


2 Answers

This then?

    DateTime lastSleep = DateTime.Now;            
    while (true)
    {
        TimeSpan span = DateTime.Now - lastSleep;
        if (span.TotalMilliseconds > 700)
        {
            Thread.Sleep(300);
            lastSleep = DateTime.Now;
        }
    }

You could use smaller numbers to get a more steady load....as long as the ratio is whatever you want. This does only use one core though, so you might have to do this in multiple threads.

like image 123
Bubblewrap Avatar answered Sep 21 '22 09:09

Bubblewrap


You could add a threaded timer that wakes up on an interval and does some work. Then tweak the interval and amount of work until you approximate the load you want.

    private void button1_Click(object sender, EventArgs e)
    {
        m_timer = new Timer(DoWork);
        m_timer.Change(TimeSpan.Zero, TimeSpan.FromMilliseconds(10));
    }

    private static void DoWork(object state)
    {
        long j = 0;
        for (int i = 0; i < 2000000; i++)
        {
            j += 1;
        }
        Console.WriteLine(j);
    }

alt text

With that and tweaking the value of the loop I was able to add 20%, 60% and full load to my system. It will scale for multiple cores using additional threads for more even load.

like image 29
Colin Gravill Avatar answered Sep 22 '22 09:09

Colin Gravill