CPU usage: a cautionary tale


Richard Russell
 

I was trying to track down the cause of excessive CPU usage in one of my programs and eventually traced it to this code:
 
      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.

Join bb4w@groups.io to automatically receive all group messages.