views:

163

answers:

2

My program's really consuming CPU time far more than I'd like (2 displays shoots it up to 80-90%). I'm using Qtimers, and some of them are as short as 2ms. At any given time, I can have 12+ timers going per display -- 2ms, 2ms, 2ms, 250ms, the rest ranging between 200ms and 500ms. Would it be better if I used threads for some or all of these (especially the short ones)? Would it make much of a difference?

+2  A: 

The main time issue is going to come in on the high priority timers. First off make sure you really need these every 2ms, secondly to overcome some of the overhead in the QTimer class you could group your 3 2ms timeouts into one, and everytime it goes off just execute the 3 sections of code sequentially. I don't think threading will solve the issue though.

DeusAduro
Well, this short timer rate is based on RS-232 transfer speeds at 19200 baud rate. One timer for reading, one timer for writing, and one timer for checking the buffer. The 250ms timer is for response timeouts (the display should respond within that time). The rest of the timers update display text, or some other operation. I can definitely combine the three timers in one though.
Scott
Ah, no wonder then. Sorry, but your question really now look like "Do I need a normal or Philips screwdriver to put a nail in?". No, you need a hammer. And in this case, you probably need interrupt-driven I/O. Does your Qt serial class support `QIODevice::readyRead` ?
MSalters
+1  A: 

The 2 ms seams suspect to me. People have been reading and writing to Serial Ports at 19200 baud for years (for example on 486 hardware) without overloading the cpu. Maybe your approach is wrong.

What api are you using to access the port? I sounds like you are polling them, if the api supports blocked reads and writes this would be a much better approach.

The simplest would then be to put the read and write in their own thread, and use blocking reads in a loop, then your thread will only be busy when there is data to read and you are processing it. Your application should know when it needs to write, so the right thread should wait on a condition variable, when data is available this condition is triggered waking up the write thread.

There are probably easier single threaded approaches to this as I am sure the first applications to read and write on serial ports (e.g. x modem) were not multi-threaded, but I do not know them but they should be documented in the api you are using.

iain
486? I've used it on a 4.77 Mhz 8086. It did help that my PC had the 16550A UART with 16 byte buffers; 19200 baud is about 2000 bytes per second, which means you need to empty the buffer only every 8 ms. And it's interrupt-driven so no fancy timers needed.
MSalters
I didn't get a 16550A until I got my 486, my 386SX had a 16550, same speed but without the buffer.
iain