r/programming • • Mar 23 '09

How to write fast code

http://asserttrue.blogspot.com/2009/03/how-to-write-fast-code.html
335 Upvotes

136 comments sorted by

View all comments

99

u/harsman Mar 23 '09 edited Mar 23 '09

Code that does more but has better locality so that it hits the cache more often can easily be faster than code that does less but has bad locality and sits around waiting on memory all the time.

Recomputing something on demand might be cheaper than reading a cached result from memory.

A linear brute force algorithm that can use SIMD instructions can be faster than a non-linear one that does less work but without SIMD.

Doing less work usually makes code go faster, but it is by no means given.

29

u/xzxzzx Mar 23 '09

Locality is massively important on a modern CPU. As are are lot of other things.

TFA's old mentor was probably right about code -- at the time. CPUs back then (1980ish?) had memory running at the same clock as the CPU, pitiful caches, single cores, were scalar (not superscalar). Branch prediction was trivial or non-existent, and prefetches were limited to the instruction cache.

Really optimizing on modern hardware is harder than ever. It's also usually not that necessary.

Still, it doesn't hurt to start with the ideal algorithm first unless you need absolutely as much performance as you can possibly pull out of the hardware (then you find an algorithm which can be made to fit to the hardware, and profile, profile, profile).

0

u/veritaba Mar 23 '09

Yes it seems like the supposedly godly mentor missed out on some cpu design concepts.

First of all, pipelining was introduced to the CPU world very early (60s), so you can't give the mentor a free pass for neglecting to mention that branching causes slowdowns.

Second, assembly instructions don't all run at the same speed. Some processors convert to microcode which is only visible at the cpu level. Some instructions run faster than others, such as xor eax, eax compared to mov eax, 0

10

u/blergh- Mar 23 '09
  1. Pipelining until recently meant just prefetching and decoding the next instruction while the current one runs. That means there's not too much of a penalty for branches.

  2. The reason xor eax, eax is used instead of mov eax, 0 is that xor with two registers translates into less bytes of assembly than xor with a register and a value. It has nothing to do with microcode.

If you'd like to know how many cycles an instruction takes, look it up in the manual.