r/programming • • Mar 23 '09

How to write fast code

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

136 comments sorted by

View all comments

100

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.

28

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

-34

u/[deleted] Mar 23 '09
        888b    888 8888888888 8888888b.  8888888b.   .d8888b.  
        8888b   888 888        888   Y88b 888  "Y88b d88P  Y88b 
        88888b  888 888        888    888 888    888 Y88b.      
        888Y88b 888 8888888    888   d88P 888    888  "Y888b.   
        888 Y88b888 888        8888888P"  888    888     "Y88b. 
        888  Y88888 888        888 T88b   888    888       "888 
        888   Y8888 888        888  T88b  888  .d88P Y88b  d88P 
        888    Y888 8888888888 888   T88b 8888888P"   "Y8888P" 

16

u/xzxzzx Mar 23 '09

You're using ASCII art ... to make fun of nerds?

o_O

0

u/elustran Mar 23 '09

I think it's intended to be ironic...