28 points · by ingve · 8y ago · 11 comments
Prefer giving your optimising compiler a prefetch hint, it will be better at guessing the distance and be less architecture-dependant.
Benchmaking on realistic workloads is crucial for this kind of work. If you can’t measure the benefit, leave it out, because what is harmless on one arch can be measurably harmful on another. As if that wasn’t bad enough, results can and do differ between compilers, too, even on the same arch.
This optimization worked fine the Core 2 architecture. After moving to Westmere, the optimization didn't have any significant effect (I doubt the hardware was doing list prefetching, so some other bottleneck was preventing it from being effective). On the other hand, enabling hyper-threading gave a near 100% speedup (the application was trivially parallelizable and already parallelized via openmp).
[1] Actually for portability, I ended up doing explicit throwaway reads in the released code instead of using prefetch instructions.
[2] The linked list was not optimal but the vectors were shuffled around a lot so a fast splice was useful. Prefetching the vector itself would still have been a win though.
A better trick for hiding memory latency in these cases is to interleave multiple searches (perhaps of different instances of the data structure). For example you can write binary_tree.find_both(key1, key2) that's almost as fast (on large trees) as finding a single key.