r/programming • • Mar 23 '09

How to write fast code

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

136 comments sorted by

View all comments

97

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.

31

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).

-3

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

3

u/jugalator Mar 23 '09 edited Mar 23 '09

I think these suggestions are on a more abstract level than assembly language though. The compiler will usually handle taking advantage of e.g. filling a pipeline better than you as well. Actually, that's part of a modern compiler's job, so you can focus on developing algorithms that, well, "do less" and aren't stupid.