Socket Reading causes CPU to max out
Hi,
Ok, so im trying to asynchronously read data from a QTcpSocket, in a slot connected to its readyRead() signal.
Every time the signal gets emitted, I readAll() and append it to a QByteArray buffer, after each readAll() call, I check to see if the buffer has the termination bytes in to know if I have all my data so I can stop.
With 3mb of data coming down, it works fine but CPU usage is way to high and im after a solution if possible.
Code:
void nclient::readSocket() // connected to QTcpSocket::readyRead()
{
buffer.append(client->readAll()); // put available bytes into buffer
...
// buffer testing logic to find if all data has been received
}
Its defiantly the readAll() calls that are maxing out the CPU and not my checking code, I can only assume its down to the large volumes of readyRead() signals, I think its 1 per packet and there's obviously 1000s of packets for a 3mb transmission...
I don't know the size of the data in advance, so I cant enforce a minimum bytesAvailable size before reading data, all I know is how the stream ends.
I would be really grateful if anyone can point me in the right direction, basically so I can download the stream without resource hogging and stop when I find the ending bytes.
Thanks,
Jack
Re: Socket Reading causes CPU to max out
I'd rather think this is append() that is eating all your cpu power, not readAll().
Re: Socket Reading causes CPU to max out
Hmm thanks alot, assuming the append() call is what's sucking up resources, could you recommend a more efficient approach to keeping a buffer maintained in memory?
Re: Socket Reading causes CPU to max out
Why assume when you can check it out? Surround the calls with QTime::elapsed and you'll be certain.
If you append to a large buffer, the buffer has to be reallocated and the data has to be copied to a new buffer which takes time. Either allocate some space in advance or store the data in several buffers.