KEMBAR78
[mypyc] Simplify comparison of tuple elements by p-sawicki · Pull Request #19396 · python/mypy · GitHub
Skip to content

Conversation

p-sawicki
Copy link
Collaborator

Got rid of unnecessary operations when comparing tuple elements returns a bit primitive.

Example code:

def f(x: tuple[float], y: tuple[float]) -> bool:
    return x == y

IR before:

def f(x, y):
    x, y :: tuple[float]
    r0, r1 :: float
    r2 :: bit
    r3 :: object
    r4 :: i32
    r5 :: bit
    r6, r7, r8 :: bool
L0:
    r0 = x[0]
    r1 = y[0]
    r2 = r0 == r1
    r3 = box(bit, r2)
    r4 = PyObject_IsTrue(r3)
    r5 = r4 >= 0 :: signed
    if not r5 goto L5 (error at f:2) else goto L1 :: bool
L1:
    r6 = truncate r4: i32 to builtins.bool
    if not r6 goto L2 else goto L3 :: bool
L2:
    r7 = 0
    goto L4
L3:
    r7 = 1
L4:
    return r7
L5:
    r8 = <error> :: bool
    return r8

IR after:

def f(x, y):
    x, y :: tuple[float]
    r0, r1 :: float
    r2 :: bit
    r3 :: bool
L0:
    r0 = x[0]
    r1 = y[0]
    r2 = r0 == r1
    if not r2 goto L1 else goto L2 :: bool
L1:
    r3 = 0
    goto L3
L2:
    r3 = 1
L3:
    return r3

Tested using the following benchmark:

def f(x: tuple[float,float], y: tuple[float,float]) -> bool:
    return x == y

def bench(n: int) -> None:
    for x in range(n):
        lhs = (float(x), float(x * 2))
        rhs = (float(x), float(x * 3))
        f(lhs, rhs)

from time import time
bench(1000)
t0 = time()
bench(50 * 1000 * 1000)
print(time() - t0)

Execution time goes from ~315ms to ~150ms on my machine.

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice perf win!

@JukkaL JukkaL merged commit f9fe331 into python:master Jul 8, 2025
13 checks passed
@JukkaL
Copy link
Collaborator

JukkaL commented Jul 8, 2025

I measured the impact to mypy self check runtime using misc/perf_compare.py -- this improved performance by 0.4%, which very good (measured 100 samples)!

@JukkaL
Copy link
Collaborator

JukkaL commented Jul 8, 2025

this improved performance by 0.4%

I did another measurement and it appears to be random noise, unfortunately.

@p-sawicki p-sawicki deleted the simplify-tuple-elem-compare branch July 8, 2025 16:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants