问题描述
在我的计算机中,此代码需要17秒(十亿次):
In my computer this code takes 17 seconds (1000 millions times):
static void Main(string[] args) {
var sw = new Stopwatch(); sw.Start();
int r;
for (int i = 1; i <= 100000000; i++) {
for (int j = 1; j <= 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;
}
而Math.DivRem需要27秒.
while Math.DivRem takes 27 seconds.
.NET反射器为我提供了Math.DivRem的这段代码:
.NET Reflector gives me this code for Math.DivRem:
public static int DivRem(int a, int b, out int result)
{
result = a % b;
return (a / b);
}
CIL
.method public hidebysig static int32 DivRem(int32 a, int32 b, [out] int32& 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
}
从理论上讲,它对于具有多核的计算机可能会更快,但实际上它不需要首先进行两次操作,因为x86 CPU在执行操作时会返回商和余数使用DIV或IDIV的整数除法( http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-2.html#HEADING2-451 )!
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 both the quotient and remainder when they do an integer division using DIV or IDIV (http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_6/CH06-2.html#HEADING2-451)!
推荐答案
Grrr.该功能存在的唯一原因是为此利用了CPU指令,而他们甚至没有这样做!
Grrr. The only reason for this function to exist is to take advantage of the CPU instruction for this, and they didn't even do it!
这篇关于为什么Math.DivRem如此低效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!