Why is minus slower than mod?

in this particular case

    Const debugTime As String = "hh:mm:ss.fffffff"
    Dim i As Integer

    Debug.Print("Start " & Now.ToString(debugTime))
    For i = 0 To 4000000
        j = 5 - 4
    Next
    Debug.Print("End " & Now.ToString(debugTime))

    Debug.Print("Start " & Now.ToString(debugTime))
    For i = 0 To 4000000
        j = 5 Mod 4
    Next
    Debug.Print("End " & Now.ToString(debugTime))

result

Start 05: 33: 39.8281250

End 05: 33: 39.8437500

Start 05: 33: 39.8437500

End 05: 33: 39.8437500

* EDIT *

changed the code to look like this:

    Const debugTime As String = "hh:mm:ss.fffffff"
    Dim i As Long, j As Integer
    Dim r As Random

    r = New Random(1)
    Debug.Print("Start " & Now.ToString(debugTime))
    For i = 0 To 400000000
        j = 5 - r.Next(1, 5)
    Next
    Debug.Print("End " & Now.ToString(debugTime))

    r = New Random(1)
    Debug.Print("Start " & Now.ToString(debugTime))
    For i = 0 To 400000000
        j = 5 Mod r.Next(1, 5)
    Next
    Debug.Print("End " & Now.ToString(debugTime))

now minus faster ...

Start 05: 49: 25.0156250

End 05: 49: 35.7031250

Start 05: 49: 35.7031250

End 05: 49: 48.2187500

+3
source share
3 answers
  • Benchmarking at such tiny time intervals gives you wide access to the timer granularity issues that you see here.
  • Your code does not actually calculate anything, since you have a constant both times.

, - , JIT , , - , .

+7

. , , .

UPDATE: Mac OS X, Intel 64. :

a.asm: yasm -f macho64 a.asm

SECTION .text
global _bmod, _bmin
_bmod:  push rdx
    push rbx
    mov rcx, 1000000000
    mov rdi, 5
    mov rsi, 4
.bmod:  mov rax, rdi
    mov rbx, rsi
    xor rdx, rdx
    div rbx             ; div instruction stores the mod in rdx.
    dec rcx
    jnz .bmod
    pop rbx
    pop rdx
    ret

_bmin:  push rdx
    push rbx
    mov rcx, 1000000000
    mov rdi, 5
    mov rsi, 4
.bmin:  mov rax, rdi
    mov rbx, rsi
    sub rax, rbx
    dec rcx
    jnz .bmin
    pop rbx
    pop rdx
    ret

a.c: gcc -m64 a.c a.o

#include <time.h>
#include <stdio.h>

void bmod();
void bmin();

main() {
    time_t timex,timex2;
    time(&timex);
    bmod();
    time(&timex2);
    printf("Mod: %d\n", timex2 - timex);
    time(&timex);
    bmin();
    time(&timex2);
    printf("Min: %d\n", timex2 - timex);
}

, MacBook Air:

Mehrdad-Air:~ Mehrdad$ yasm -f macho64 a.asm 
Mehrdad-Air:~ Mehrdad$ gcc -m64 -O0 a.c a.o
Mehrdad-Air:~ Mehrdad$ ./a.out 
Mod: 14
Min: 2

, , .

+5

, , System.Diagnostics.Stopwatch() , , , DateTime.Now

  Dim t = new System.Diagnostics.Stopwatch()
  t.Start

  ''Do Stuff...

  Debug.Print(t.Elapsed)
  t.Stop

: ( Jon :

  Dim t = System.Diagnostics.Stopwatch.StartNew

  ''Do Stuff...

  Debug.Print(t.Elapsed)
  t.Stop

)

+3

All Articles