CPU usage: a cautionary tale

Discussions related to mouse, keyboard, fonts and Graphical User Interface
RichardRussell
Posts: 593
Joined: Tue 15 Oct 2019, 09:10

CPU usage: a cautionary tale

Post by RichardRussell »

I was trying to track down the cause of excessive CPU usage in one of my programs and eventually traced it to this code:

Code: Select all

      REPEAT
        OFF
        K% = INKEY(4)
      UNTIL K% <> -1
At first glance this looks entirely innocuous: it should spend nearly all its time in INKEY and use very little CPU. Indeed if you run the profiler that is exactly what it tells you, yet Task Manager was showing a CPU usage of around 50%! How is that possible?

It turns out that the culprit is that innocent-looking OFF. Because it's (quite unnecessarily) inside the loop it gets executed around 25 times a second, and OFF is equivalent to VDU 23,1,0,0,0,0,0,0,0,0! So what it was actually doing was keeping the GUI thread awake pretty much continuously processing those VDU commands.

Moving the OFF outside the loop reduced the CPU usage to close to zero.
I am suffering from 'cognitive decline' and depression. If you have a comment about the style or tone of this message please report it to the moderators by clicking the exclamation mark icon, rather than complaining on the public forum.

michael
Posts: 43
Joined: Mon 02 Apr 2018, 17:13

Re: CPU usage: a cautionary tale

Post by michael »

Because it's (quite unnecessarily) inside the loop it gets executed around 25 times a second
Interesting.

p_m21987
Posts: 150
Joined: Mon 02 Apr 2018, 21:51

Re: CPU usage: a cautionary tale

Post by p_m21987 »

This is interesting to think about.
I noticed the OFF being inside the loop right away. Over the years I've developed an instinctive/intuitive feeling for this kind of thing. I don't like to have unnecessary stuff inside my loops.

Ivan
Posts: 100
Joined: Tue 07 May 2019, 16:47

Re: CPU usage: a cautionary tale

Post by Ivan »

It feels good when I can push an if statement outside a loop by rewriting code.
BBC Model B - 1984-1989. 6502 assembler, Unicomal 1988-1994, Some C and C++, Pascal 1990-1994. Bought a copy of BBC-BASIC 2007, but started to program at a daily basis 2019.