Skip to content

Clip width 1 lines to the image - #10610

Merged
radarhere merged 4 commits into
mainfrom
clip-width-1-lines
Nov 25, 2026
Merged

radarhere merged 4 commits into
mainfrom
clip-width-1-lines

Conversation

@aclark4life

Copy link
Copy Markdown
Member

Lines of width 1 were not clipped to the image before stepping through them, so the time grew with the length of the line. For example, line((0, 0, 2**30, 1)) on a 16x16 image took 1.24 s. The line deltas were also calculated in int, which could overflow for very distant coordinates.

This clips the line to the image before drawing it, and uses 64-bit arithmetic for the deltas. The example now takes no measurable time.

For dashed lines (#9490, not yet released):

  • The dash position is kept modulo the pattern length, and the pixels skipped before the image edge are counted, so a clipped dashed line keeps the same phase as the full line. Previously should_draw_dash() walked the pattern from the start of the line for each pixel.
  • A pattern whose values add up to 0, such as dash=(0,), now draws nothing, rather than looping forever. Negative values are treated as 0.

🤖 Generated with Claude Code

Only step through the part of a line inside the image, using 64-bit
arithmetic for the line deltas. Keep the dash phase of a clipped dashed
line, and draw nothing for a dash pattern of zero length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codspeed

codspeed Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 3 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 668 untouched benchmarks
⏩ 352 skipped benchmarks1


Comparing clip-width-1-lines (0dd5018) with main (af804a5)

Open in CodSpeed

Footnotes

  1. 352 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@radarhere

Copy link
Copy Markdown
Member

@codspeedbot explain

@codspeed

codspeed Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

@codspeedbot explain

The regression comes from the line() per-pixel loop in src/libImaging/Draw.c, not from the new clipping. The dashed and non-dashed loops were merged into one, so the solid-line path now does more work on every pixel.

What the profile shows (test_draw_lines[1237x811-L], base vs head flame graph)

  • Total: 661.5 µs → 767.9 µs.
  • point8 did not change (313.8 µs → 314.4 µs). clip_line costs 2.7 µs, because it runs once per segment.
  • All of the extra time is self time of line() itself: about 290 µs → 389 µs.
  • Most of it is memory-access cost ("caches": 371.9 µs → 457 µs). Instructions add only about 21 µs.
  • The other functions in the profile moved by less than 1%. So the "different software environment" warning does not explain this change. The code does.

Why

The benchmark draws a 16-segment zigzag that stays inside the image, about 20,000 pixels per call. Clipping removes nothing here, so only the cost per pixel matters.

On main, the solid-line Bresenham loop was its own loop. I compiled Draw.c from both commits with -O3 and looked at the generated code. In the main build, the loop counter, x0, y0 and e stay in registers across the indirect point() call. Each step only reloads a few constants from the stack.

On this branch, one loop handles both cases (dash == NULL || should_draw_dash(...), dash != NULL && ++pos == period). The variables are now 64-bit, and pos, period and dash are also live across the call. That is more values than the callee-saved registers can hold. So the compiler keeps i, e, x0 and y0 on the stack and writes them back on every step, for example addq $1,0x10(%rsp), add %esi,0x4(%rsp) and mov %rax,0x8(%rsp). Each step also tests dash. The simulation instrument charges every memory access, which is why the "caches" part grew. On real hardware, store-to-load forwarding hides some of this cost. But the extra loads and stores are real work.

How to fix it

Keep the clipping and the 64-bit setup in clip_line, but split the loop again: one plain Bresenham loop for dash == NULL (the same as on main, starting from the clipped x0, y0, e, n), and a separate loop for dashes. The loop variables can probably go back to int after clipping: n is at most the image size, and e stays within ±2*da. Check this before narrowing e, because da can be close to 2^32. That should bring test_draw_lines back to the main numbers and keep the gains for distant coordinates and dashes.

Comment this and I'll do it:

@codspeedbot fix this regression
Summary
  • Warming up the performance wizard...
  • Read the pull request change — Read the pull request change
  • Compare flame graphs of base and head — Extra cost is all in line() loop self time; point8 unchanged. Generated code shows loop state spilled to the stack.
  • Write the explanation — Write the explanation
  • Handling comment — Comment handling finished successfully

Was this response helpful? React with 👍 or 👎 to help us improve CodSpeedBot.

@akx

akx commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Why is 64-bit arithmetic needed here?

@radarhere

Copy link
Copy Markdown
Member

I've pushed commits to clip the lines in Python instead, but only if any go outside the image. That should address this edge case without affecting normal performance.

I've also adjusted the validation to raise an error if a dash value is zero or negative.

Comment thread src/PIL/ImageDraw.py
Comment on lines +338 to +350
def coord_at_angle(
coord: Sequence[float], angle: float
) -> tuple[float, ...]:
x, y = coord
angle -= 90
distance = width / 2 - 1
return tuple(
p + (math.floor(p_d) if p_d > 0 else math.ceil(p_d))
for p, p_d in (
(x, distance * math.cos(math.radians(angle))),
(y, distance * math.sin(math.radians(angle))),
)
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Function declared inside a loop?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

That's already in main, this PR just adjusts the indent -

def coord_at_angle(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ah. Still... maybe something to fix?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I've created #10621

Could you explain a bit why this is problematic?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Python will create new function objects needlessly in the loop (and I suspect PyPy won't JIT them as well, not that it matters much here).

That PR works, but just lifting this up to e.g. global or class scope (and adding the width it captured from the closure as an argument) would do the trick too.

@radarhere
radarhere merged commit cd853a4 into main Nov 25, 2026
133 of 135 checks passed
@radarhere
radarhere deleted the clip-width-1-lines branch November 25, 2026 01:06
strike19 added a commit to strike19/Pillow that referenced this pull request Nov 25, 2026
Restricting lines to the image in Python (python-pillow#10610) moves their end points, so
that Bresenham's algorithm sets different pixels inside the image than for the
whole line, and the same line moved by whole pixels no longer gives the same
pixels.

Instead, keep the end points and skip the steps before and after the image
in C. The error term for the first visible step follows from the minor axis
offset k(i) = floor((2 * minor * i + major) / (2 * major)), computed with
64-bit integers, as the coordinates are 32-bit and the product of the
smaller delta and the number of skipped steps can reach 2**64. The dash
position is taken modulo the length of the pattern, so that long dashed lines
take no time either.

Solid lines that lie inside the image take the loops they had before, so
ordinary lines are no slower; only a line that reaches outside the image uses
the new calculation.

Python now only restricts lines that reach outside the range of C ints.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants