runtime icon indicating copy to clipboard operation
runtime copied to clipboard

.Net 4.6 RC x64 is twice as slow as x86 (release version)

Open BijanVan opened this issue 11 years ago • 10 comments

Net 4.6 RC x64 is twice as slow as x86 (release version):

Consider this piece of code:

class SpectralNorm
{
    public static void Main(String[] args)
    {
        int n = 5500;
        if (args.Length > 0) n = Int32.Parse(args[0]);

        var spec = new SpectralNorm();
        var watch = Stopwatch.StartNew();
        var res = spec.Approximate(n);

        Console.WriteLine("{0:f9} -- {1}", res, watch.Elapsed.TotalMilliseconds);
    }

    double Approximate(int n)
    {
        // create unit vector
        double[] u = new double[n];
        for (int i = 0; i < n; i++) u[i] = 1;

        // 20 steps of the power method
        double[] v = new double[n];
        for (int i = 0; i < n; i++) v[i] = 0;

        for (int i = 0; i < 10; i++)
        {
            MultiplyAtAv(n, u, v);
            MultiplyAtAv(n, v, u);
        }

        // B=AtA         A multiplied by A transposed
        // v.Bv /(v.v)   eigenvalue of v 
        double vBv = 0, vv = 0;
        for (int i = 0; i < n; i++)
        {
            vBv += u[i] * v[i];
            vv += v[i] * v[i];
        }

        return Math.Sqrt(vBv / vv);
    }


    /* return element i,j of infinite matrix A */
    double A(int i, int j)
    {
        return 1.0 / ((i + j) * (i + j + 1) / 2 + i + 1);
    }

    /* multiply vector v by matrix A */
    void MultiplyAv(int n, double[] v, double[] Av)
    {
        for (int i = 0; i < n; i++)
        {
            Av[i] = 0;
            for (int j = 0; j < n; j++) Av[i] += A(i, j) * v[j];
        }
    }

    /* multiply vector v by matrix A transposed */
    void MultiplyAtv(int n, double[] v, double[] Atv)
    {
        for (int i = 0; i < n; i++)
        {
            Atv[i] = 0;
            for (int j = 0; j < n; j++) Atv[i] += A(j, i) * v[j];
        }
    }

    /* multiply vector v by matrix A and then by matrix A transposed */
    void MultiplyAtAv(int n, double[] v, double[] AtAv)
    {
        double[] u = new double[n];
        MultiplyAv(n, v, u);
        MultiplyAtv(n, u, AtAv);
    }
}

On my machine x86 release version takes 4.5 seconds to complete, while the x64 takes 9.5 seconds. Is there any specific flag/setting needed for the x64?

===== UPDATE =========

It turns out that RyuJIT has a role in this issue. If useLegacyJit is enabled in app.config, the the result is different and this time x64 is faster.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
  </startup>
  <runtime>
      <useLegacyJit enabled="1" />
 </runtime>
</configuration>

Reference: http://stackoverflow.com/questions/30195356/net-4-6-rc-x64-is-twice-as-slow-as-x86-release-version

BijanVan avatar May 13 '15 15:05 BijanVan

Now that's an interesting issue. I think it's helpful to look at a simplified example that illustrates the problem:

static double A(int i, int j) {
    return 1.0 / ((i + j) * (i + j + 1) / 2 + i + 1);
}

static void Multiply(double[] x, double[] y) {
    for (int i = 0; i < y.Length; i++) {
        double sum = 0.0;
        for (int j = 0; j < x.Length; j++)
            sum += A(i, j) * x[j];
        y[i] = sum;
    }
}

In conditions similar to the one in the original code (10 iterations, 5500 elements) this code takes ~2800ms to execute on my machine. If the legacy x64 JIT is used then the time drops to ~1400ms. The 2x difference from the original example persists.

The interesting part is that there's very little difference between the code generated (for the inner loop) by the legacy JIT and RyuJIT:

Legacy JIT:

01: 8D 46 FF             lea         eax,[rsi-1]  
02: 0F AF C6             imul        eax,esi  
03: 99                   cdq  
04: 2B C2                sub         eax,edx  
05: D1 F8                sar         eax,1  
06: 8D 44 08 01          lea         eax,[rax+rcx+1]  
07: F2 0F 2A C0          cvtsi2sd    xmm0,eax  
08: F2 0F 10 0D 49 00 00 00 movsd       xmm1,mmword ptr [7FFF23600648h]  
09: F2 0F 5E C8          divsd       xmm1,xmm0  
10: F2 43 0F 59 4C 23 10 mulsd       xmm1,mmword ptr [r11+r12+10h]  
11: F2 0F 58 CA          addsd       xmm1,xmm2  
12: 66 0F 28 D1          movapd      xmm2,xmm1  
13: FF C5                inc         ebp  
14: FF C6                inc         esi  
15: 49 83 C4 08          add         r12,8  
16: 3B EF                cmp         ebp,edi  
17: 7C C6                jl          00007FFF236005E4  

RyuJIT:

01: 41 8D 04 31          lea         eax,[r9+rsi]  
02: 8D 50 01             lea         edx,[rax+1]  
03: 0F AF C2             imul        eax,edx  
04: 99                   cdq  
05: 2B C2                sub         eax,edx  
06: D1 F8                sar         eax,1  
07: 42 8D 44 08 01       lea         eax,[rax+r9+1]  
08: F2 0F 2A C8          cvtsi2sd    xmm1,eax  
09: F2 0F 10 15 31 00 00 00 movsd       xmm2,mmword ptr [7FFF235F0610h]  
10: F2 0F 5E D1          divsd       xmm2,xmm1  
11: 48 63 C6             movsxd      rax,esi  
12: 0F 28 CA             movaps      xmm1,xmm2  
13: F2 0F 59 4C C1 10    mulsd       xmm1,mmword ptr [rcx+rax*8+10h]  
14: F2 0F 58 C1          addsd       xmm0,xmm1  
15: FF C6                inc         esi  
16: 44 3B DE             cmp         r11d,esi  
17: 7F C5                jg          00007FFF235F05BF  

The instruction count is the same. All the expensive instructions (divsd, cvtsi2sd, imul etc.) exists in both versions. The legacy JIT eliminated i + j and a 32-64 bit sign extension at the expense of introducing additional induction variables. Neither loops are 16 byte aligned. Hmm...

mikedn avatar May 13 '15 19:05 mikedn

The question has been asked on StackOverflow but is relevant to repeat here

"is the slowness in the Jitting? or in the jitted code? ie.. is it just taking a long time to jit the code, then execute the code fast or is it actually executing the code slowly? You do this by running the test multiple times and throwing out the first result."

by Erik Funkenbusch on SO.

We can also compare pre-jitted code performance.

A reasonable theory is that RyuJIT takes longer for its optimization to kick in?

Eyas avatar May 13 '15 19:05 Eyas

I can't speak for @BijanVan but my timings were obtained after running the Multiply method once to avoid including JIT time in timings. Besides, the legacy JIT is known to be slow compared to RyuJIT.

mikedn avatar May 13 '15 19:05 mikedn

cc @vancem @CarolEidt @BruceForstall

billwert avatar May 13 '15 20:05 billwert

The problem appears to be the useless movaps from line 12:

12: 0F 28 CA             movaps      xmm1,xmm2  
13: F2 0F 59 4C C1 10    mulsd       xmm1,mmword ptr [rcx+rax*8+10h]  
14: F2 0F 58 C1          addsd       xmm0,xmm1  

If this is rewritten as:

12: 
13: F2 0F 59 4C C1 10    mulsd       xmm2,mmword ptr [rcx+rax*8+10h]  
14: F2 0F 58 C1          addsd       xmm0,xmm2

then the 2x difference magically disappears. Well, it's not the movaps itself as there's no way that it could cause such a large difference. The following version works fine too:

12: 0F 28 CA             movaps      xmm3,xmm2  
13: F2 0F 59 4C C1 10    mulsd       xmm3,mmword ptr [rcx+rax*8+10h]  
14: F2 0F 58 C1          addsd       xmm0,xmm3  

The difference is that another register is used instead of xmm1. That's likely because xmm1 was used earlier and reusing it here somehow affects instruction parallelism. Seems odd but I don't know enough about instruction scheduling to comment.

Anyway, it's the JIT's fault that the useless movaps is there.

mikedn avatar May 13 '15 20:05 mikedn

/cc @sivarv

Looks like this was reported on StackOverflow and Connect as well.

BruceForstall avatar May 13 '15 20:05 BruceForstall

Turns out that movaps is just a victim of an earlier problem - cvtsi2sd. That one should be preceded by a xorps xmm1, xmm1 to avoid introducing a false dependency.

mikedn avatar May 13 '15 22:05 mikedn

I could repro 2x perf between RyuJIT and Legacy JIt64 on my intel box. But on my Amd64 machine, RyuJIT performance is on par with Jit64.

Cvtsi2sd does a partial write of lower 8-bytes with upper bytes of xmm register unmodified. For the repro case xmm1 is partially written but there are further uses of xmm1 down the code. This creates a false dependency between cvtsi2sd and other instructions that use xmm1 which affects instruction parallelism. Indeed modifying codegen of genIntToFloatCast() to emit a "xorps xmm1, xmm1" fixes perf regression.

Workaround: Perf regression could also be avoided if we reverse the order of operands in multiply operation in MultiplyAv/MultiplyAvt methods

void MultiplyAv(int n, double[] v, double[] Av)
{
    for (int i = 0; i < n; i++)
    {
        Av[i] = 0;
        for (int j = 0; j < n; j++)  
              Av[i] += v[j] * A(i, j);  //  order of operands reversed
    }
}

sivarv avatar May 15 '15 19:05 sivarv

I have built a minimal benchmark that reproduce the issue. I use BenchmarkDotNet v0.7.4 (it run the target method several times in different processes, make warmup, calculates statistic, and so on). Maybe it will be useful for you.

The code:

[Task(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.LegacyJit)]
[Task(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)]
public class Cpu_Ilp_RyuJit
{
    private double[] x = new double[11];

    [Benchmark]
    public double Calc()
    {
        double sum = 0.0;
        for (int i = 1; i < x.Length; i++)
            sum += 1.0 / (i * i) * x[i];
        return sum;
    }
}

The results on my laptop:

// BenchmarkDotNet=v0.7.4.0
// OS=Microsoft Windows NT 6.2.9200.0
// Processor=Intel(R) Core(TM) i7-4702MQ CPU @ 2.20GHz, ProcessorCount=8
// CLR=MS.NET 4.0.30319.0, Arch=64-bit  [RyuJIT]
Common:  Type=Cpu_Ilp_RyuJit  Method=Calc  Mode=Throughput  Platform=X64  .NET=Current

       Jit |  AvrTime |   StdDev |        op/s |
---------- |--------- |--------- |------------ |
 LegacyJit | 44.79 ns | 0.135 ns | 22325756.62 |
    RyuJit | 85.19 ns | 0.254 ns | 11737931.94 |

You can find the benchmark in the BenchmarkDotNet.Samples (see commit https://github.com/AndreyAkinshin/BenchmarkDotNet/commit/118e2f0de5308a8fac33816c9a5fc4ab6db43512)

LegacyJIT-x64 ASM:

;        double sum = 0.0;
 xorpd       xmm2,xmm2  
;        for (int i = 1; i < x.Length; i++)
 mov         rdx,qword ptr [rcx+8]  
 mov         rcx,qword ptr [rdx+8]  
 cmp         ecx,1  
 jle         00007FF9141145D2  
 mov         r8d,1  
 mov         r9d,8  
 nop         dword ptr [rax]  
;            sum += 1.0 / (i * i) * x[i];
Loop:
 mov         eax,r8d  
 imul        eax,r8d  
 cvtsi2sd    xmm0,eax  
 movsd       xmm1,mmword ptr [7FF9141145E0h]  
 divsd       xmm1,xmm0  
 mulsd       xmm1,mmword ptr [rdx+r9+10h]  
 addsd       xmm1,xmm2  
 movapd      xmm2,xmm1  
;        for (int i = 1; i < x.Length; i++)
 inc         r8d  
 add         r9,8  
 cmp         r8d,ecx  
 jl          Loop  
;        return sum;
 movapd      xmm0,xmm2  
 ret  

RuyJIT-x64 ASM:

;         double sum = 0.0;
 sub         rsp,28h  
 vxorpd      xmm0,xmm0,xmm0  
;        for (int i = 1; i < x.Length; i++)
 mov         eax,1  
 mov         rdx,qword ptr [rcx+8]  
 mov         ecx,dword ptr [rdx+8]  
 cmp         ecx,1  
 jle         00007FF9140E4385  
;            sum += 1.0 / (i * i) * x[i];
Loop:
 mov         r8d,eax  
 imul        r8d,eax  
 vcvtsi2sd   xmm1,xmm1,r8d  
 vmovsd      xmm2,qword ptr [7FF9140E4398h]  
 vdivsd      xmm2,xmm2,xmm1  
 mov         r8,rdx  
 cmp         eax,ecx  
 jae         ThrowException  
 movsxd      r9,eax  
 vmovaps     xmm1,xmm2  
 vmulsd      xmm1,xmm1,mmword ptr [r8+r9*8+10h]  
 vaddsd      xmm0,xmm0,xmm1  
;        for (int i = 1; i < x.Length; i++)
 inc         eax  
 cmp         ecx,eax  
 jg          Loop
 add         rsp,28h  
 ret  
ThrowException:
 call        ThrowExceptionMethod
 int         3 

AndreyAkinshin avatar May 16 '15 02:05 AndreyAkinshin

@sivarv Please close when the change makes it's way here.

cmckinsey avatar May 28 '15 00:05 cmckinsey