V
V
Vitaly Pukhov2015-01-31 04:30:23
.NET
Vitaly Pukhov, 2015-01-31 04:30:23

How to optimize Serial.WriteLine?

There is a function that receives data from the queue and sends it to the COM port. this thread is 100% of the time sending data (lines of 16 characters), 1 at a time. COM works at the maximum speed available to it (115 thousand), everything would be fine, but this function eats up the CPU very much, on my 4-core Phenomenon it easily eats up 30% of the CPU, as for me this function is quite primitive (sending data) and should not be so strong there is a CPU, can it be optimized somehow?

Queue sd = new Queue();
        void Sender()
        {
            Serial.WriteLine((string)sd.Dequeue());
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Oxoron, 2015-01-31
@Neuroware

I see two possible bugs.
1. Only one message is sent in the method. This means that the method is called about 115 thousand times per second (I'm not sure that I named the number correctly, but the essence is clear). You can measure the number of messages in the queue and pass it to the Sender() method. It turns out

void Sender(int messageQty)
        {
                for(int i=0; i< messageQty; i++)
                {
                        Serial.WriteLine((string)sd.Dequeue());
                }               
        } // Интересно, вызовы Dequeue можно избежать? Каким-нибудь foreach или другой структурой? Или они вообще не фатальны?

2. You have cast to a string, (string)sd.Dequeue(). He also wastes time. If possible, use Queue<string>. Alternatively, you can try using sb.Dequeue().ToString()

M
mayorovp, 2015-01-31
@mayorovp

I don't like this line: Serial.WriteLine((string)sd.Dequeue());
How do you check that there is something in the sd queue at all?
Show a larger piece of the program, there you probably have an active expectation.

E
Eddy_Em, 2015-01-31
@Eddy_Em

I suspect that if it is written directly on the registers, then there will be no problems!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question