Search code examples
if-statementconditional-statementscoding-stylesoftware-designinstruction-set

How comparison operator utilizes CPU cycle in programming


If I have following conditions then which comparison condition executes fast(in terms of CPU cycles and time):

if(1 < 2)

if(1 < 100)

Solution

  • There is no dynamic values in your example, only constants, so compiler (either AOT or JIT one) could optimize out both conditions and compiled code would not contain ifs. Thus no difference between these conditions.

    Even if there were dynamic values, both conditions would have the same speed. Because comparison to a value is fast operation, comparison to 2 either to 1000 will have the same time.

    E.g. for x86 64-bit. if (value < 2) would translate into something like:

    cmp rax, 2
    jl condition_succeded_label
    

    From Instruction latencies and throughput for AMD and Intel x86 processors by Torbjörn Granlund, Intel/AMD CPUs have 1 cycle latency for CMP instruction (L64 below), and each core of modern Intel/AMD CPUs can do up to 4 CMP instructions in parallel (T64, a throughput, below). Regardless of the constant operand, either 2 or 1000. CMP thouthput

    What may differ is branch misprediction, when CPU predicts wrong branch, it may cost 10-20 cycles (reference from Wikipedia) of CPU or more (depending on CPU model, data in cache, memory speed). While comparison itself takes 0.25-1 cycles as in the table above.