Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Today I learned loops are slow
#11
We (as programmers) already have a term for when something takes a long time. Even on a computer you own and are simply programming for pleasure. The term is "expensive operation." The reason is, at the machine code level, some operations take more time to execute, e.g. adding two numbers is "less expensive" than calculating a square root. So often programmers will find workarounds. Like dividing by a power of 2, e.g. 4,8,16,32, etc. Division is a very expensive operation. But shifting something one or more bits left or right is much cheaper by comparison. If you have a program where several million calculations have to be done, shifting an integer 1 bit right is the same as dividing by 2. Some compilers check, and when possible, substitute shift left or right for some multiplication or division operation, respectively.

Looping is another one of those expensive operations because of the set-up at the start of the loop and the process on each iteration. There are tricks that compiler writers use, such as if a loop will have a relatively small number of repetitions, that not doing the loop is cheaper, at a small increase in code size, the compiler will "unroll" the loop and repeat the instructions used in the loop inline, repeating the number of times it would have looped. Sometimes the "savings" are amazing, code runs twice as fast. Or maybe you don't get that much improvement, maybe you only get 10%, but on large operations (e.g. the multi-million or multi-billion calculation example) the savings can be significant.
While 1
   Fix Bugs
   report all bugs fixed
   receive bug report
end while
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I have learned something new: how to get a run-time syntax error TDarcos 2 964 10-02-2024, 07:04 PM
Last Post: TDarcos
  A little bit of spark fun today TerryRitchie 2 834 05-18-2024, 12:59 AM
Last Post: bobalooie
  Loops alternate recursive ways bplus 10 2,024 02-01-2023, 02:05 PM
Last Post: Dimster

Forum Jump:


Users browsing this thread: 1 Guest(s)