CPU usage: a cautionary tale

Discussions related to mouse, keyboard, fonts and Graphical User Interface
RichardRussell
Posts: 533
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.
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: 41
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.