5

C++ Summary

Using the #pragma intrinsic command in the preprocessor section of your code will greatly increase the speed of most math function calls.

#pragma intrinsic(sqrt, pow)

The above code allows most math functions calls to be sent directly to the math co-processor rather than being sent to the function stack.

Question

Is there any way to do this in C#? Other than rewriting the built in functions to do something similar. Like for example, it is common to do power of two, so this would be appropriate, but it is not what I am looking for:

public double Pow2(double value)
{
    return (value * value);
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nahydrin
  • 13,197
  • 12
  • 59
  • 101

1 Answers1

3

C# shouldn't need "#pragma intrinsic", because:

Accessing math coprocessor from C#

The JIT compiler knows about the math coprocessor and will use it.

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • `This was part of the promise of JIT-compilation, ..., but I don't think .NET actually does that, at least in v4.` – Nahydrin Jul 05 '11 at 04:19
  • 1
    @Dark: You're quoting me out of context. That particular bit was talking about use of SIMD. – Ben Voigt Jul 05 '11 at 04:23
  • Your right, my bad. Didn't see that. So what would be a viable replacement if I want to speed up my code? – Nahydrin Jul 05 '11 at 04:24
  • There's nothing stopping .NET from substituting `SQRTSD` or `MULSD` instructions for `Math.Sqrt(x)` and `Math.Pow(x, 2)`. I don't know if it currently does this, though. C#/.NET really aren't the right tools to use if you need such micro-optimization. – Cory Nelson Jul 05 '11 at 04:29
  • @Dark: A smarter algorithm. Sometimes you can avoid the square root, i.e. `if (sqrt(x*x + y*y) < r)` can be done faster by squaring both sides: `if (x*x + y*y < r*r)`, since an extra multiply is much faster than a square root. What kind of calculation are you doing? – Ben Voigt Jul 05 '11 at 04:30
  • Also, depending on the precision you need, a lookup table can be much quicker than having the FPU do the calculation. – Ben Voigt Jul 05 '11 at 04:31
  • It's not so much one calculation, I'm looking for a good way to increase the speed of math functions. – Nahydrin Jul 05 '11 at 04:33
  • @Dark: Anyway, you should probably ask a new question, describing your calculation and asking how to speed it up. Use the `c#` and `performance` tags. – Ben Voigt Jul 05 '11 at 04:33
  • 2
    @Dark: If there was a universal way to speed up math, the compiler would already be doing it. What's left is problem-specific optimizations. And first you should use a profiler and find out what the slow areas of your program really are. – Ben Voigt Jul 05 '11 at 04:34