Retin-A For Sale, The square root is one of those basic mathematical operations that's totally ubiquitous in any game's source code, and yet also has many competing implementations and performance superstitions around it. The compiler offers a sqrt() builtin function, and so do some CPUs, but some programmers insist on writing their own routines in software, Retin-A from canadian pharmacy. And often it's really the reciprocal square root you want, for normalizing a vector, Retin-A reviews, or trigonometry. But I've never had a clear answer for which technique is really fastest, or exactly what accuracy-vs-speed tradeoffs we make with "estimating" intrinsics.

What is the fastest way to compute a square root, where can i find Retin-A online. It would seem that if the CPU has a native square-root opcode, there's no beating the hardware, but is it really true, Retin-A For Sale.

Such questions vex me, so I went and measured all the different means of computing the square root of a scalar single-precision floating point number that I could think of. After Retin-A, I ran trials on my Intel Core 2 and on the Xenon, comparing each technique for both speed and accuracy, and some of the results were surprising.

In this article I'll describe my results for the Intel hardware; next week I'll turn to the Xenon PPC, buy Retin-A no prescription.

Experimental setup


I'll post the whole source code for my tests elsewhere, but basically each of these trials consists of iterating N times over an array of floating point numbers, Retin-A recreational, calling square root upon each of them and writing it to a second output array.

[DDET (see pseudocode)]

 Retin-A For Sale, inline float TestedFunction( float x )
{
return sqrt(x); // one of many implementations..
}
void TimeSquareRoot()
{
float numbersIn[ ARRAYSIZE ]; // ARRAYSIZE chosen so that both arrays
float numbersOut[ ARRAYSIZE ]; // fit in L1 cache
// assume that numbersIn is filled with random positive numbers, and both arrays are
// prefetched to cache...
StartClockCycleCounter();
for ( int i = 0 ; i < NUMITERATIONS ; ++i )
for ( int j = 0 ; j < ARRAYSIZE ; ++j ) // in some cases I unroll this loop
{
numbersOut[j] = TestedFunction( numbersIn[j] );
}
StopClockCycleCounter();
printf( "%.3f millisec for %d floats\n", Retin-A steet value,
ClockCycleCounterInMilliseconds(), ARRAYSIZE * NUMITERATIONS );

// now measure accuracy
float error = 0;
for ( int i = 0 ; i < ARRAYSIZE ; ++i )
{
double knownAccurate = PerfectSquareRoot( numbersIn[i] );
error += fabs( numbersOut[i] - knownAccurate ) / knownAccurate ;
}
error /= ARRAYSIZE ;
printf( "Average error: %.5f%%\n", Retin-A class, error * 100.0f );
}


[/DDET]

In each case I verified that the compiler was not eliding any computations (it really was performing ARRAYSIZE × NUMITERATIONS many square roots), that it was properly inlining the tested function, and that all the arrays fit into L1 cache so that memory latency wasn't affecting the results. I also only tested scalar square root functions — SIMD would clearly be the fastest way of working on large contiguous arrays, Retin-A brand name, but I wanted to measure the different techniques of computing one square root at a time, as is usually necessary in gameplay code. Buy Retin-A without prescription, Because some of the speedup techniques involve trading off accuracy, I compared the resulting numbers against the perfectly-accurate double-precision square root library routine to get an average error for each test run.

And I performed each run multiple times with different data, averaging the final results together, Retin-A For Sale.

x86 results

I ran my tests on a 2.66Ghz Intel Core 2 workstation. An x86 chip actually has two different means of performing scalar floating-point math, buy no prescription Retin-A online. By default, the compiler uses the old x87 FPU, Buy generic Retin-A, which dates back to 1980 with a stack-based instruction set like one of those old RPN calculators. In 1999, Intel introduced SSE, which added a variety of new instructions to the processor, Retin-A treatment. SSE is mostly thought of as a SIMD instruction set — for operating on four 32-bit floats in a single op — but it also includes an entire set of scalar Retin-A For Sale, floating point instructions that operate on only one float at a time. It's faster than the x87 operations and was meant to deprecate the old x87 pathway. However, Effects of Retin-A, both the MSVC and GCC compilers default to exclusively using the x87 for scalar math, so unless you edit the "code generation" project properties panel (MSVC) or provide a cryptic obscure command line option (GCC), you'll be stuck with code that uses the old slow way.

I timed the following techniques for square root:


  1. The compiler's built in sqrt() function (which compiled to the x87 FSQRT opcode)

  2. The SSE "scalar single square root" opcode sqrtss, order Retin-A no prescription, which MSVC emits if you use the _mm_sqrt_ss intrinsic or if you set /arch:SSE2

  3. The "magic number" approximation technique invented by Greg Walsh at Ardent Computer and made famous by John Carmack in the Quake III source code.

  4. Taking the estimated reciprocal square root of a via the SSE opcode rsqrtss, and multiplying it against a to get the square root via the identity x / √x = √x.

  5. Method (4), Retin-A without a prescription, with one additional step of Newton-Raphson iteration to improve accuracy.

  6. Method (5), with the loop at line 13 of the pseudocode above unrolled to process four floats per iteration.


I also tested three ways of getting the reciprocal square root: Carmack's technique, the rsqrtss SSE op via compiler intrinsic, and rsqrtss with one Newton-Raphson step, Retin-A pics.

The results, for 4096 loops over 4096 single-precision floats, Retin-A without prescription, were:


SQUARE ROOT




























MethodTotal timeTime per floatAvg Error
Compiler sqrt(x) /
x87 FPU FSQRT
404.029ms24ns0.0000%
SSE intrinsic ssqrts 200.395ms11.9ns0.0000%
Carmack's Magic Number rsqrt * x 72.682ms4.33ns0.0990%
SSE rsqrtss * x 20.495ms1.22ns0.0094%
SSE rsqrtss * x
with one NR step
53.401ms3.18ns0.0000%
SSE rsqrtss * x
with one NR step, unrolled by four
48.701ms2.90ns0.0000%





RECIPROCAL SQRT
















MethodTotal timeTime per floatAvg Error
Carmack's Magic Number rsqrt 59.378ms3.54ns0.0990%
SSE rsqrtss 14.202ms0.85ns0.0094%
SSE rsqrtss
with one NR step
45.952ms2.74ns0.0000%

Discussion

Looking at these results, it's clear that there's a dramatic difference in performance between different approaches to performing square root; which one you choose really can have a significant impact on framerate and accuracy. My conclusions are:

Don't trust the compiler to do the right thing. The received wisdom on performance in math functions is usually "don't reinvent the wheel; the library and compiler are smart and optimal." We see here that this is completely wrong, and in fact calling the library sqrt(x) causes the compiler to do exactly the worst possible thing, Retin-A For Sale. The compiler's output for y = sqrt(x); is worse by orders of magnitude compared to any other approach tested here, Retin-A alternatives.

The x87 FPU is really very slow. Intel has been trying to deprecate the old x87 FPU instructions for a decade now, but no compiler in the business defaults to using the new, Retin-A gel, ointment, cream, pill, spray, continuous-release, extended-release, faster SSE scalar opcodes in place of emulating a thirty-year-old 8087. In the case of y = sqrt(x) , by default MSVC and GCC emit something like


fld DWORD PTR [ecx]
fsqrt ;; slow x87 flop
fstp DWORD PTR [eax]

But if I set the /arch:SSE2 option flag, telling the compiler "assume this code will run on a machine with SSE2", Retin-A from canada, it will instead emit the following, which is 2x faster. Retin-A dose,

sqrtss xmm0, DWORD PTR [ecx] ;; faster SSE scalar flop
movss DWORD PTR [eax], xmm0

There was a time when not every PC on the market had SSE2, meaning that there was some sense in using the older, Retin-A price, coupon, more backwards-compatible operations, but that time has long since passed. SSE2 was introduced in 2001 with the Pentium 4 Retin-A For Sale, . Retin-A canada, mexico, india, No one is ever going to try to play your game on a machine that doesn't support it. If your customer's PC has DirectX 9, it has SSE2.

You can beat the hardware. The most surprising thing about these results for me was that it is faster to take a reciprocal square root and multiply it, Retin-A no prescription, than it is to use the native sqrt opcode, by an order of magnitude. Retin-A pictures, Even Carmack's trick, which I had assumed was obsolete in an age of deep pipelines and load-hit-stores, proved faster than the native SSE scalar op. Part of this is that the reciprocal sqrt opcode rsqrtss is an estimate, accurate to twelve bits; but it only takes one step of Newton's Method to converge that estimate to an accuracy of 24 bits while still being four times faster than the hardware square root opcode, Retin-A For Sale.

The question that then bothered me was, no prescription Retin-A online, why is SSE's built-in-to-hardware square root opcode slower than synthesizing it out of two other math operations. The first hint came when I tried unrolling the loop so that it performed four ops inside the inner for():


for ( int i = 0 ; i < NUMITERATIONS ; ++i )
for ( int j = 0 ; j < ARRAYSIZE ; j += 4 ) // in some cases I unroll this loop
{
numbersOut[j + 0] = TestedSqrt( numbersIn[j + 0] );
numbersOut[j + 1] = TestedSqrt( numbersIn[j + 1] );
numbersOut[j + 2] = TestedSqrt( numbersIn[j + 2] );
numbersOut[j + 3] = TestedSqrt( numbersIn[j + 3] );
}

// two implementations of

As you can see from the results above, Retin-A maximum dosage, when TestedSqrt was the rsqrtss followed by a multiply and one step of Newton iteration, unrolling the loop this way provided a modest 8.8% improvement in speed. But when I tried the same thing with the "precise square root" op sqrtss, the difference was negligible:


SSE sqrt: 200.395 msec
average error 0.0000%

SSE sqrt, Retin-A from mexico, unrolled four: 196.741 msec
average error 0.0000%

What this suggests is that unrolling the loop this way allowed the four rsqrt paths to be pipelined, so that while an individual rsqrtss might take 6 cycles to execute before its result was ready, What is Retin-A, other work could proceed during that time so that the four square root operations in the loop overlapped. On the other hand, the non-estimated sqrtss op apparently cannot be overlapped; one sqrt must finish before the next can begin. A look at the Intel® 64 and IA-32 Architectures Optimization Reference Manual confirms: sqrtss Retin-A For Sale, is an unpipelined instruction.

Pipelined operations make a big difference. When the CPU hits an unpipelined instruction, Retin-A natural, every other instruction in the pipeline has to stop and wait for it to retire before proceeding, so it's like putting the handbrake on your processor. Retin-A photos, You can identify nonpipelined operations in appendix C of the Optimization Reference Manual as the ones that have a throughput equal to latency and greater than 4 cycles.

In the case of ssqrt, the processor is probably doing the same thing internally that I'm doing in my "fast" function — taking an estimated reciprocal square root, improving it with Newton's method, and then multiplying it by the input parameter, Retin-A long term. Taken all together, this is far too much work to fit into a single execution unit, so the processor stalls until it's all done. But if you break up the work so that each of those steps is its own instruction, then the CPU can pipeline them all, and get a much higher throughput even if the latency is the same.

Pipeline latency and microcoded instructions are a much bigger deal on the 360 and PS3, whose CPUs don't reorder operations to hide bubbles; there the benefit from unrolling is much greater, as you'll see next week.

Conclusion

Not all square root functions are created equal, and writing your own can have very real performance benefits over trusting the compiler to optimize your code for you (at which it fails miserably). In many cases you can trade off some accuracy for a massive increase in speed, but even in those places where you need full accuracy, writing your own function to leverage the rsqrtss op followed by Newton's method can still give you 32 bits of precision at a 4x-8x improvement over what you will get with the built-in sqrtf() function.

And if you have lots of numbers you need to square root, of course SIMD (rsqrtps) will be faster still.

Similar posts: Buy Stromectol Without Prescription. Buy Cafergot Without Prescription. Buy Temovate Cream Without Prescription. Tramadol canada, mexico, india. Temovate Cream results. Kjøpe Stromectol på nett, köpa Stromectol online.
Trackbacks from: Retin-A For Sale. Retin-A For Sale. Retin-A For Sale. Kjøpe Retin-A på nett, köpa Retin-A online. Cheap Retin-A no rx. Retin-A treatment.

26 Comments

  1. DFS says:

    Excellent excellent post! Looking forward to the 360 results.

  2. LeeN says:

    Might be worth while to make your simulation closer to the way they would be used in the real world. In my experience, rarely are we lucky enough to only have to do a square root (or any arithmetic operation) on an array of floats. In AI for example, you may only update some information once as a optimization and so in the middle of some code decide to do a distance check. With a circular HUD minimap in a game you might want to place an icon at the edge of the minimap to indicate the direction of a goal, requiring normalizing a direction and scaling it to the size of the minimap. I think the normal set of operations to do would be to do a vector subtraction, a dot product, a square root and then a division (get it, ‘normal’ :)).

  3. marco says:

    Very interesting post! Looking forward to the 360 results too.

  4. Petrocket says:

    Fantastic! Can’t wait to try these out – Maybe this is a noob question but what about and processors? Any special sauce there?

  5. Elan says:

    Petrocket: AMD, you mean? I haven’t got one to measure on, but you could try it. I’ll post my source code for the tests once I’ve cleaned it up. Based on the “Software Optimization Guide for AMD64 Processors” I’d bet the results are similar to those for Intel.

    Lee: Testing this in the a vec-norm function is a good idea; I’ll work that up. My goal really was to measure the throughput of sqrt itself, so wrapping it in too much other code starts to make measurement unreliable. What I can tell you for sure though is that unpipelined ops are particularly bad for that case, though, because it prevents the processor from reordering other instructions to run while the sqrt is cooking. rsqrt, on the other hand, is pipelined, so even though it has a six-cycle latency, the fetch stage of the Core Duo can reorganize other work to take place until the results are ready.

    DFS, marco: Thanks!

  6. Sanjay says:

    Nice work. Some minor issues:
    1. “no compiler in the business defaults to using the new, faster SSE scalar opcodes” – Apple compilers do (including their version of gcc). OSX has never used x87 by default.

    2. “it only takes one step of Newton’s Method” – I think it actually takes two steps. Intel’s RSQRTE is architected to achieve under 12 bits of precision, so in some cases you need 2 steps to get the last bit to match the hardware’s SQRT. You probably still won’t get edge cases and denormals correct with the estimate.

  7. Adrian says:

    Interesting post, I got inspried by your post and did a comparison between GPU square root routines:
    http://adrianboeing.blogspot.com/2009/10/timing-square-root-on-gpu.html

    PS: I think Sanjay is correct, the RSQRTE takes two steps (at least it does for AMD)

  8. Alex says:

    “no compiler in the business defaults to using the new, faster SSE scalar opcodes”

    64-bit gcc does by default.

  9. rsw says:

    By “average error” do you mean you simply took the mean of the signed error? I think RMS error or mean absolute error is a more useful metric here.

    Nice writeup either way.

  10. Elan says:

    Mean absolute error, of course. Otherwise I’d just be computing a random walk.

  11. S.M says:

    Before you bash gcc, did you set the “-mcpu= ” correctly for gcc ??

  12. Jason says:

    “no compiler in the business defaults to using the new, faster SSE scalar opcodes”

    AFAIK all compilers generating x64 code use SSE by default (since all 64 bit x86 CPUs have SSE, this makes sense)

  13. fioj says:

    “a cryptic obscure command line option (GCC)”

    What’s obscure about that command line option? It is well known to all GCC users, as well as the fact that GCC uses SSE floating point maths on amd64, as Alex mentioned.

  14. Elan says:

    Is someone shipping x64-only games?

  15. Elias says:

    Here is one technique you apparently haven’t tried: taking the number to the 0.5 power. How does that compare?

  16. Elan says:

    Elias: 4096 loops over 4096 floats with x = powf(x, 0.5f) took 1449.538ms, or 86.4ns/float. This is 3.6 times worse than even the compiler’s naive x87 sqrt(x), and twenty-seven times worse than rsqrtss with one step of Newton-Rhapson iteration (which is equally accurate). Taking an exponent is a function call, and a very slow function call at that.

  17. Gregory says:

    I’m curious about what’s behind StartClockCycleCounter(); and StopClockCycleCounter();

    What’s the best way to benchmark a portion of code on PC? QueryPerformanceCounter (windows only), RTDSC? something else?

    And is there a point putting the target code inside a loop?

  18. Elan says:

    We use rtdsc to implement our cycle counter, since it seems to have the best resolution of any of the timers available.

    It’s best to put target code in a loop for the same reason you would weigh rice by the thousand rather than one grain at a time on your kitchen scale: systematic and random error.

    First, there is a certain systematic error in querying the cycle counter — the StartCycleCounter() inline function call and the rtdsc op itself have some latency, and the timer is probably only accurate to within a couple of nanoseconds, measuring a single iteration of an 86ns operation would have a large relative error. On the other hand, a relative error of 10-8 in 10-3 seconds is much smaller, and so more accurate.

    Also, timings in vivo can be messy: any single iteration of the loop might take a little longer than expected because of other threads, memory bus contention, clock variability, operating system intervention, even CPU temperature. Taking multiple measurements, or a single measurement of multiple iterations, improves statistical significance and narrows the error bars.

  19. Gregory says:

    Hello Elan,

    Thank you for the answer.

    Since I posted my comment, I came across http://msdn.microsoft.com/en-us/library/bb173458(VS.85).aspx so I think I’m going to implement my high precision timer using QPC on Windows and gettimeofday on Linux and Mac.

    Or the easy way seems to be Boost.PTime

  20. Yuhong Bao says:

    “If your customer’s PC has DirectX 9, it has SSE2.”
    Not necessarily, as the graphics card choice is independent of the CPU choice.

  21. jalf says:

    Did you ever get around to cleaning up the source code?

  22. Bruce Dawson says:

    One part of the reason that the x87 square root is slower is that it is probably calculating square root to double precision. The x87 hardware defaults to calculating square root to 80-bit precision, the C run-time changes the setting so it calculates it to 64-bit precision, but if you change it to calculate it to 32-bit precision (controlfp) then it will be a bit faster. Square root and float-divide timings on x87 are both affected by the selected precision. I don’t think any other operations are.

    Of course, changing a global (well, global per-thread) setting in order to get a local optimization is pretty crazy, so your points stand.

  23. Wrong On The Internet! | Rambling Llamas says:

    [...] this guy went into it in much more thorough detail if you’re interested!) This entry was posted in [...]

  24. ns says:

    nice article!

    sqrt(x) = x*rsqrt(x) is definitely fast but suffers from a NaN problem for x==0.
    sqrt(0) = 0*rsqrt(0) = 0*(1/sqrt(0)) = 0*(1/0) = 0*INF = NaN

    using the rcp instruction (_mm_rcp_ss) computing 1/x, the square root could be computed as
    sqrt(x) = rcp( rsqrt(x) )
    This doesn’t produce a NaN
    sqrt(0) = rcp(rsqrt(0)) = 1/(1/sqrt(0)) = 1/INF = 0
    It’s still very fast (not very accurate though!)

  25. CeeG says:

    sqrt(y) give this iterate: x += 0.5*(y/x – x)
    rsqrt(y) give this iterate: x += 0.5*(x – y*x*x*x)

    - No division in the second scheme, maybe this is why rsqrt() is faster both in software and hardware design.

    1/y give this iterate: x += x*(1-y*x)

    - Maybe this is why sqrt() is an unpipelined instruction (two interleaved iterative loop).

Leave a Reply