Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Math.DivRem so inefficient?
    text
    copied!<p>In my computer this code takes 17 seconds (1000 millions times):</p> <pre><code>static void Main(string[] args) { var sw = new Stopwatch(); sw.Start(); int r; for (int i = 1; i &lt;= 100000000; i++) { for (int j = 1; j &lt;= 10; j++) { MyDivRem (i,j, out r); } } Console.WriteLine(sw.ElapsedMilliseconds); } static int MyDivRem(int dividend, int divisor, out int remainder) { int quotient = dividend / divisor; remainder = dividend - divisor * quotient; return quotient; } </code></pre> <p>while Math.DivRem takes 27 seconds.</p> <p><a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="nofollow noreferrer">.NET Reflector</a> gives me this code for Math.DivRem:</p> <pre><code>public static int DivRem(int a, int b, out int result) { result = a % b; return (a / b); } </code></pre> <h3>CIL</h3> <pre><code>.method public hidebysig static int32 DivRem(int32 a, int32 b, [out] int32&amp; result) cil managed { .maxstack 8 L_0000: ldarg.2 L_0001: ldarg.0 L_0002: ldarg.1 L_0003: rem L_0004: stind.i4 L_0005: ldarg.0 L_0006: ldarg.1 L_0007: div L_0008: ret } </code></pre> <p>Theoretically it may be faster for computers with multiple cores, but in fact it shouldn't need to do two operations in the first place, because x86 CPUs return <strong>both the quotient and remainder</strong> when they do an integer division using DIV or IDIV (<a href="http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-2.html#HEADING2-451" rel="nofollow noreferrer">http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-2.html#HEADING2-451</a>)!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload