Which is faster, while(1) or while(2)?

Asked 2 years ago, Updated 2 years ago, 144 views

In the interview, I asked which one would be faster, while(1) or while(2) Whether it's (1) or (2), it's true I said I think they'd be at the same speed while(1) is faster. Why?

while(1) {
    //What code?
}
or

while(2) {
    //What code?
}

performance c while-loop

2022-09-21 15:12

1 Answers

To see how two codes actually run, The assemblies of the two codes must be compared in gcc.

int main(void)
{
    while(1)
    {
    }

    return 0;
}


int main(void)
{
    while(2)
    {
    }

    return 0;
}

Based on the results, The assembly of the two codes is the same with or without the optimization option (-O0). So there's no speed difference between the two repetitive doors.

For any optimization (gcc main.c-S-masm=intel+option) both always produced the same results.

At -O0:

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    push    rbp
    .seh_pushreg    rbp
    mov rbp, rsp
    .seh_setframe   rbp, 0
    sub rsp, 32
    .seh_stackalloc 32
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

From -O1:

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .text
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    sub rsp, 40
    .seh_stackalloc 40
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

At -O2/-O3:

    .file   "main.c"
    .intel_syntax noprefix
    .def    __main; .scl    2;  .type   32; .endef
    .section    .text.startup,"x"
    .p2align 4,,15
    .globl  main
    .def    main;   .scl    2;  .type   32; .endef
    .seh_proc   main
main:
    sub rsp, 40
    .seh_stackalloc 40
    .seh_endprologue
    call    __main
.L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

Can you see that the repetition sentence is the following form using any optimization method?

 .L2:
    jmp .L2
    .seh_endproc
    .ident  "GCC: (tdm64-2) 4.8.1"

The important thing is here,

.L2:
    jmp .L2

I'm not good at assembly language, but this is an unconditional jump to L2 without comparing it with an unconditional loop. If you change this to c code,

L2:
    goto L2;

This is.

To sum up, When a repeat statement is compiled into the assembly language, if it has a constant value, the compiler preprocesses it.

Therefore, while(1), while(2), while(1==1), while(3==3&&4==4), while(0.1+0.2) do not differ in assembly speed when compiled.


2022-09-21 15:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.