Playing with the CPU pipeline

This article will show how basic knowledge of a modern CPU’s instruction pipeline can help micro-optimise code at very little cost, using a real world example: the approximation of a trigonometric function. All this without necessarily having to look at lines of assembly code.

Evaluating polynomials

Who needs polynomials anyway? We’re writing games, not a computer algebra system, after all. But wait! ​Taylor series are an excellent mathematical tool for approximating certain classes of functions. For instance, this is the Taylor series of sin(x) near x = 0:

Truncating the series at the 15th power will compute sin(x) with an absolute error no greater than 1e-11 in the range [-π/2; π/2], and 2e-16 in the range [-π/4; π/4].

However, a better approximation known as the minimax polynomial (probably featured in an upcoming article) will give a maximum absolute error of about 2e-16 on the whole [-π/2; π/2] range:

We are down to 9 multiplications and 7 additions. There is probably no way to be faster, is there? Let’s see…

Timings

Here are the timings in nanoseconds for the above code, compared with the glibc’s sin() function. The test CPU is an Intel® Core™ i7-2620M CPU at 2.70GHz. The functions were compiled using -O3 -ffast-math:

function

sin

sin1

sin2

sin3

nanoseconds per call

22.518

16.406

16.658

25.276

Wait, what? Our superbly elegant function, performing only 9 multiplications, is actually slower than the 64-multiplication version? Which itself is as fast as the 16-multiplication one? Surely we overlooked something.

That’s right. We ignored the CPU pipeline.

The instruction pipeline

In order to execute an instruction, such as “add A and B into C”, a CPU needs to do at least the following:

fetch the instruction (ie. read it from the program’s memory)

decode the instruction

read the instruction’s operands (ie. A and B)

execute the instruction

write the result in memory or in registers (in our case, C)

On a modern Intel® CPU, the execution step only accounts for 1/10 or even 1/16 of the total execution time. The idea behind ​pipelining is simple: while executing an instruction, the CPU can often already read the operands for the next one.

But there is a problem with this strategy: if the next instruction depends on the result of the current one, the CPU cannot read the next operands yet. This is called a ​read-after-write hazard, and most usually causes a pipeline stall: the CPU just does nothing until it can carry on.

For the sake of simplicity, imagine the CPU’s pipeline depth is 3. At a given time, it can fetch, execute and finish one instruction:

●

instruction is being fetched, executed or finished

○

instruction could start, but needs to wait for the result of a previous instruction

This is how the CPU would execute A = (a + b) * (c + d):

time →

total: 7

1

B = a + b

●

●

●

2

C = c + d

●

●

●

3

A = B * C

○

○

●

●

●

The c + d operation can be started very early because it does not depend on the result of a + b. This is called ​instruction-level parallelism. However, the final B * C operation needs to wait for all previous instructions to finish.

Since every operation in sin3() depends on the previous one, this is how it would execute that function:

time →

total: 48

1

x2 = x * x

●

●

●

2

A = a7 * x2

○

○

●

●

●

3

A += a6

○

○

●

●

●

4

A *= x2

○

○

●

●

●

5

A += a5

○

○

●

●

●

6

A *= x2

○

○

●

●

●

7

A += a4

○

○

●

●

●

8

A *= x2

○

○

●

●

●

9

A += a3

○

○

●

●

●

10

A *= x2

○

○

●

●

●

11

A += a2

○

○

●

●

●

12

A *= x2

○

○

●

●

●

13

A += a1

○

○

●

●

●

14

A *= x2

○

○

●

●

●

15

A += a0

○

○

●

●

●

16

A *= x

○

○

●

●

●

These 9 multiplications and 7 additions are done in 48 units of time. No instruction-level parallelism is possible because each instruction needs to wait for the previous one to finish.

The secret behind sin2()’s performance is that the large number of independent operations allows the compiler to reorganise the computation so that the instructions can be scheduled in a much more efficient way. This is roughly how GCC compiled it:

time →

total: 30

1

x2 = x * x

●

●

●

2

A = a7 * x2

○

○

●

●

●

3

x3 = x2 * x

●

●

●

4

A += a6

○

●

●

●

5

B = a1 * x3

●

●

●

6

x5 = x3 * x2

●

●

●

7

A *= x2

●

●

●

8

C = a2 * x5

○

●

●

●

9

B += x

●

●

●

10

x7 = x5 * x2

●

●

●

11

A += a5

●

●

●

12

D = a3 * x7

●

●

●

13

B += C

●

●

●

14

x9 = x7 * x2

●

●

●

15

B += D

○

●

●

●

16

E = a4 * x9

●

●

●

17

x11 = x9 * x2

●

●

●

18

B += E

○

●

●

●

19

A *= x11

●

●

●

20

A += B

○

○

●

●

●

These 13 multiplications and 7 additions are executed in 30 units of time instead of 48 for the previous version. The compiler has been rather clever here: the number of ○’s is kept small.

Going further

We have seen that increasing the number of operations in order to break dependencies between CPU instructions allowed to help the compiler perform better optimisations taking advantage of the CPU pipeline. But that was at the cost of 40% more multiplications. Maybe there is a way to improve the scheduling without adding so many instructions?

Luckily there are other ways to evaluate a polynomial.

Even-Odd form and similar schemes

Consider our 8th order polynomial:

Separating the odd and even coefficients, it can be rewritten as:

Which using Horner’s form yields to:

This polynomial evaluation scheme is called the Even-Odd scheme. It only has 9 multiplications and 7 additions (only one multiplication more than the optimal case). It results in the following C code:

One more instruction and two units of time better. That’s slightly better, but still not as good as we would like. One problem is that a lot of time is lost waiting for the value x6 to be ready. We need to find computations to do in the meantime to avoid pipeline stalls.

High-Low form

Instead of splitting the polynomial into its even and odd coefficients, we split it into its high and low coefficients:

Finally! We now schedule as well as GCC, and with 11 multiplications instead of 13. Still no real performance gain, though.

Pushing the limits

Can we do better? Probably. Remember that each ○ in the above table is a pipeline stall, and any instruction we would insert there would be basically free.

Note the last instruction, A *= x. It causes a stall because it needs to wait for the final value of A, but it would not be necessary if A and B had been multiplied by x beforehands.

Here is a way to do it (bold instructions indicate a new instruction or a modified one):

time →

total: 27

1

x2 = x * x

●

●

●

2

B = x2 * a7

○

○

●

●

●

3

A = x2 * a3

●

●

●

4

x4 = x2 * x2

●

●

●

5

B += a6

●

●

●

6

A += a2

●

●

●

7

x8 = x4 * x4

●

●

●

8

B *= x2

●

●

●

9

A *= x2

●

●

●

10

x3 = x2 * x

●

●

●

11

B += a5

●

●

●

12

A += a1

●

●

●

13

C = a0 * x

●

●

●

14

B *= x2

●

●

●

15

A *= x3

●

●

●

16

x9 = x8 * x

●

●

●

17

B += a4

●

●

●

18

A += C

●

●

●

19

B *= x9

○

●

●

●

20

A += B

○

○

●

●

●

Excellent! Just as many instructions as GCC, but now with fewer pipeline stalls. I don’t know whether this scheduling is optimal for the (incorrect) assumption of a 3-stage pipeline, but it does look pretty good. Also, loading a0, a1 etc. from memory hasn't been covered for the sake of simplicity.

Anyway, we just need to write the code corresponding to this behaviour, and hope the compiler understands what we need:

Conclusion

It’s time to check the results! Here they are, for all the functions covered in this article:

function

sin

sin1

sin2

sin3

sin4

sin5

sin6

sin7

nanoseconds per call

22.518

16.406

16.658

25.276

18.666

18.582

16.366

17.470

Damn. All these efforts to understand and refactor a function, and our best effort actually performs amongst the worst!

What did we miss? Actually, this time, nothing. The problem is that GCC didn't understand what we were trying to say in sin7() and proceeded with its own optimisation ideas. Compiling with -O3 instead of -O3 -ffast-math gives a totally different set of timings:

function

sin

sin1

sin2

sin3

sin4

sin5

sin6

sin7

nanoseconds per call

22.497

30.250

19.865

25.279

18.587

18.958

16.362

15.891

There. We win eventually!

There is a way to still use -ffast-math yet prevent GCC from trying to be too clever. This might be preferable because we do not want to lose the benefits of -ffast-math in other places. By using an architecture-specific assembly construct, we can mark temporary variables as used, effectively telling GCC that the variable needs to be really computed and not optimised away:

This works on the x86_64 architecture, where "+x" indicates the SSE registers commonly used for floating point calculations, and on the PowerPC, where "+f" can be used. This approach is not portable and it is not clear what should be used on other platforms. Using "+m" is generic but often means a useless store into memory; however, on x86 it is still a noticeable gain.

And our final results, this time with the full -O3 -ffast-math optimisation flags:

Can you use -ffast-math and -fno-unsafe-math-optimizations to avoid GCC reordering your code? Regrouping of floating point arithmetic is an "unsafe" optimization since it can change the result (due to different rounding).

what is this gcc version? If your processor is capable of, and gcc is recent enough(>4.6, I think) the -ftree-vectorizer option is included into O3, and it should kick in while calculating polynomials.

1) If you just focus on writing clean and understandable code, the compiler will usually do a pretty good job at optimizing it.

2) If you do decide to hand-optimize your code, be sure to carefully measure the results because it could just as well have the opposite effect.

I've seen a lot of situations where people tried to outsmart a compiler only to make things worse in both performance and maintainability. Micro-optimizations such as these are rarely needed in practice and should always be very carefully considered.

Very informative report but I think it is based on a wrong assumption: it is not simply the pipeline. The i7 (and many more before that!) has a particular type of run-time optimization in the form of a dual pipeline with registers renaming - which is why the execution needs to wait for the previous result to be available.

It would be interesting to evaluate the impact of Hyperthreading (Linux typically divides the dual pipelines to run more processes at the same time, loosing on this particular type of optimization). Also, this should be evaluated on an ARM core, which is very likely not to have this extra boost and probably won't show this discrepancy. I think the comment is interesting but not across the board.

This article is showing very well how basic knowledge of a modern CPU’s instruction pipeline can help micro-optimise code at very little cost, using a real world example. Thanks for it and carry on it. To get electrical safety matting Click here ​http://electricalmattingco.co.uk/

A superior all assignment Help reviews offered by this website with the advantage of online support with high proficiency level based on its latest research and information by professional reviews writers. Wide ranges of
subjects are covered with separate writers for each subject.
​http://www.bestwritersreviews.com/a-review-on-allassignmenthelp-com