Re: big cpu consumption
On Sun, 17 Aug 2008, black-white wrote:
if ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
break;//here is the place where cpu is consumed!
}
That's what we call a busy-wait, and it is indeed a very good way to waste
all your CPU time. You could try something like this:
while ((numBytesRead = line.read(data, 0, bufferLengthInBytes)) == -1) {
try {
Thread.sleep(t) ;
}
catch (InterruptedException e) {
// can probably ignore this
}
}
Where t is a duration in milliseconds. This basically means that your
program will wait for a while before trying to read data again. It won't
be consuming CPU while it waits.
The problem is picking the right value for t. If it's too long, you run
the risk of the line's buffer overflowing while the reader thread sleeps.
If it's too short, you'll use too much CPU time.
I'd set it based on a calculation of how long the buffer will take to
fill. Like this:
float dataRate = format.getFrameRate() * format.getFrameSize() ; // in bytes per second
float timeToFill = line.getBufferSize() / dataRate ; // in seconds
long t = (long)((timeToFill * f) * 1000) ;
Where f is a fraction, saying how full you want the buffer to get between
reads; i'd set it to 0.5, so the buffer will be half full. That should
mean that if your thread is a bit slow at waking up, there's still little
chance of overflow. You might need to adjust this downwards if you find
there are overflow problems.
Another option would be to set the time adaptively, based on how long the
last sleep was, and how full the buffer got. That's a bit more
complicated, but you can probably work it out.
The underlying problem is that there's no way to read data from a line in
a blocking way. This is a design fault in the library, sadly.
tom
--
History, I believe, furnishes no example of a priest-ridden people
maintaining a free civil government. -- Thomas Jefferson