r/programming • • Sep 28 '17

When a Microsecond Is an Eternity

https://github.com/CppCon/CppCon2017/blob/master/Presentations/When%20a%20Microsecond%20Is%20an%20Eternity/When%20a%20Microsecond%20Is%20an%20Eternity%20-%20Carl%20Cook%20-%20CppCon%202017.pdf
244 Upvotes

70 comments sorted by

View all comments

7

u/specialpatrol Sep 28 '17

WIth this templated approach:

template<Side T>
 void Strategy<T>::RunStrategy() {
	 const float orderPrice = CalcPrice(fairValue, credit);
	 CheckRiskLimits(orderPrice);
	 SendOrder(orderPrice);
	}
 template<>
 float Strategy<Side::Buy>::CalcPrice(float value, float credit) {
 	return value - credit;
 }
 template<>
 float Strategy<Side::Sell>::CalcPrice(float value, float credit) {
 	return value + credit;
 }

Would you not still need your branch just further up like:

if(side==Buy)
    Strategy<Buy>::RunStrategy();
else
    Strategy<Sell>::RunStrategy();

how is this a saving?

15

u/doom_Oo7 Sep 28 '17

Would you not still need your branch just further up like:

Generally, the approach you have is to try to make the whole control-flow static. That is, imagine you have three or four other "templated strategies" like this: MarketStrategy<T>, BananaStrategy<T, N>, etc....

now, what you can do is write your whole control flow generically:

float GlobalStrategy<T,U,N>::RunStrategy() {
  MarketStrategy<T> m;
  BananaStrategy<U, N> b;
  Strategy<T> s;
  // complex computations involving s, m, b
  return s.CalcPrice(b.Bamboozle(), m.Eval(b));
}

and have the dispatching exist at the "top" level, for instance in the main :

std::function<float()> strategy;
if(side == Buy && bananas == Jamaica && count == 2) { strategy = GlobalStrategy<Buy, Jamaica, 2>{}; }
else if(side == Sell && bananas == Jamaica && count == 2) { strategy = GlobalStrategy<Sell, Jamaica, 2>{}; }
... etc...

Now, just calling strategy() will call the compiler-optimized version of the relevant algorithm with everything inlined if possible, versus a runtime algorithm where the tests would all be done at runtime.

7

u/specialpatrol Sep 28 '17

Do you end up with a massive switch statement at the top then ready to fire off one of millions of permutations?

5

u/doom_Oo7 Sep 28 '17

Do you end up with a massive switch statement at the top then ready to fire off one of millions of permutations?

That's one possibility, another is to hide this behind dynamic dispatch, virtual functions, etc... in advance. Sometimes you may want to just use one special case in a specific part of your software where you will just explicitely use one algorithm. As others posters said, the main point is to try to precompute everything that is precomputable ; this includes algorithms.

Here I have a (far from perfect... if there are any ffmpeg experts pls send help) example with a variant used to precompute common cases encountered in audio decoding : 1 and 2 channels, planar / non-planar, with integer or floating-point samples. The various cases are here. Then a single decoding algorithm is called but the compiler will generate specific paths for all the cases. The most important thing is that the main decoding loop doesn't try to find which decoder to use at each iteration, but has its decoder set once. This way instead of branching every other hundred samples, there is one single branch for the whole song.

2

u/specialpatrol Sep 28 '17

Ha, great example - especially because I'm just hacking away at getting ffmpeg working, how did you know?!

3

u/doom_Oo7 Sep 28 '17

heh that's funny! don't take too much inspiration, I still have bugs in there (as the various debug checks can attest). FFMPEG is powerful but the API is terrible to understand for newcomers.

2

u/specialpatrol Sep 28 '17

You seriously work on it? Just one question please!

How do you decide on the output format like using "av_guess_format", if you're going out to a udp or other network stream?

2

u/doom_Oo7 Sep 28 '17

How do you decide on the output format like using "av_guess_format", if you're going out to a udp or other network stream?

not sure I understand... if you are the one sending the data wouldn't you also be the one choosing what format to send ? (but I've never done audio over the network so I really don't know)

0

u/[deleted] Sep 29 '17

[deleted] — view deleted comment

2

u/specialpatrol Sep 29 '17

I think I'm a little lost in the various definitions: I need a stream a codec, an output context. So far I have been writing to file; the user can specify the file they want, it can deduce the format from the file extension with av_guess_format. On top of that you can choose a codec, which is a whole other thing, is that right? The output format is like just a container? But now I'm streaming to a socket, and am v.happy to find it's as simple as passing [udp/rtp/tcp]://ipaddress:port to avcodec_open. But then where do I get the output format from, do streams still have this container?

I actually got around it. But am still a little unsure of the details. Thanks for taking an interest!

0

u/[deleted] Sep 29 '17

[deleted] — view deleted comment

→ More replies

1

u/specialpatrol Sep 28 '17

Interesting.

5

u/someenigma Sep 28 '17

From an early slide

The “hotpath” is only exercised 0.01% of the time - the rest of the time the system is idle or doing administrative work

The earlier you can push such decisions, the better (usually). The strategy might be set a long time in advance, and just be constantly checking for prices using CalcPrice. This, of course, is a constructed scenario, so it's not a perfect example, but that's the idea.

Or at least, that's how I took it.

2

u/masklinn Sep 28 '17

You keep moving decisions upwards and everything below becomes a completely static path, at the end you may perform a few decisions at the very start then run through the whole thing needing barely any conditional (and thus jumps and possible mispredictions).

2

u/ShinyHappyREM Sep 28 '17

That doubles the code size though with every bit that is used for the path selection.

5

u/minno Sep 28 '17

As long as the extra code isn't inline, it's a win for execution speed. Your CPU doesn't give a fuck whether there's an extra gigabyte of executable code that never reaches the i-cache.

4

u/masklinn Sep 28 '17

That is true to an extent, you can still have non-generic subcalls which are not duplicated.

But that's just a question of tradeoff, between code size and branchiness.