views:

90

answers:

4

I need to test some communication libraries and need to keep the server busy so that I can test timeouts, but I am unable to use sleep() as it causes problems during testing.

Is there a common algorithm I can use to keep a process busy? I'm not concerned with running the CPU hot, simply keeping the process from returning for a number of seconds without expending too many resources.

If I could define the time to keep the process busy for, that would be useful.

+2  A: 

That really depends on how you want to keep the process "busy". There is a big difference between a process that is busy crunching numbers, to one that is busy using io or one that continuously requires work from the kernel.

If you want to test that your code times out correctly, I would suggest creating the delay in the other end. If you want to test that your code behaves correctly when the server is under high load, I would suggest adding some more details about the environment you expect your app to run under - such as what other apps will be using up resources at the same time.

kasperjj
"There is a big difference between a process that is busy crunching numbers, to one that is busy using io or one that continuously requires work from the kernel." Is there? What ever the process is doing it's still "busy", and that's all I need to do - delay the process from responding. :)
digitala
If you just want to keep the process active using cpu, just calculate factorials or fibonacci numbers.
kasperjj
A: 

Simple:

while(time() < stopSleepTime)
{
    //Do something bogus like sending a webrequest or microsleep, something that takes time
}

This should pretty much fry the cpu :-P

Alxandr
Nope, that will possibly keep one core busy, but even then, depending on what "bogus" stuff you do, the scheduler could easily juggle it around to allow for the other process to not experience timeout.s
kasperjj
A: 

You could try solving the Traveling Salesman for a set of randomly chosen points.

Justin L.
A: 

If sleep() causes problems, you just want to busy wait:

while(time() < stopSleepTime) {};

There are sure to be other, more accurate solutions if you offer a specific environment.

Mark Hurd
Why the downvote? Sure the answer isn't as complete as kasperjj's but the question is vague enough that a busy wait is a simple solution.
Mark Hurd