Skip to content

Inline fast path for OutputStream::put - #2504

Closed
nikosavola wants to merge 3 commits into
KLayout:masterfrom
nikosavola:pr-stream-put-inline
Closed

nikosavola wants to merge 3 commits into
KLayout:masterfrom
nikosavola:pr-stream-put-inline

Conversation

@nikosavola

Copy link
Copy Markdown
Contributor
  • OutputStream::put and put_raw were defined in tlStream.cc, so every 2 or 4 byte field the GDS2 writer emits paid a call into the tl library and a byte-by-byte copy
  • they are now defined in the class in tlStream.h, so callers can inline them. When the chunk fits in the buffer they just memcpy and advance the position. Text mode and buffer-full cases go to the old code, now called put_slow and put_raw_slow
  • separate commit: put_raw_slow uses memcpy instead of fast_copy, which read and wrote unsigned long at unaligned addresses. That is undefined behavior and UBSan flags it. With gcc it also makes writes of 1000 bytes and more 1.2x to 3.3x faster, the table is in the commit
  • new test for writes across the buffer boundary, including empty and larger-than-buffer chunks
case before ms after ms speedup
GDS2 write (vexriscv) 120.1 85.5 1.41x
OASIS write (vexriscv) 116.7 114.5 1.02x
GDS2 read (vexriscv) 138.8 138.3 1.00x

Xeon Gold 6248, gcc 13 -O2, before and after alternated on one pinned core. All six rounds agree on the GDS2 write row.

- put and put_raw were out-of-line, so every 2 or 4 byte GDS2 record field paid a call plus a byte-wise copy
- the inline versions memcpy into the buffer when the chunk fits, text mode and buffer-full cases stay out-of-line
- fast_copy casts the buffer and source pointers to unsigned long *, but both can have any alignment, so this is undefined behavior. UBSan reports it in tlStreamTests: "store to misaligned address ... for type 'unsigned long', which requires 8 byte alignment"
- gcc -O2 turns fast_copy into a plain 8 byte loop while memcpy uses the SIMD libc version, so larger writes get faster
- clang on arm64 auto-vectorizes the loop, there it was about 15% faster than memcpy for 20000 byte chunks (Apple M5, noisy)

| chunk bytes | fast_copy ms | memcpy ms | speedup |
|---:|---:|---:|---:|
| 4 | 2214 | 2216 | 1.00x |
| 100 | 109.8 | 107.5 | 1.02x |
| 1000 | 46.0 | 39.0 | 1.18x |
| 20000 | 132.6 | 40.4 | 3.28x |
| 1048576 | 110.7 | 60.6 | 1.83x |

2 GiB written through OutputStream::put into a null delegate. Xeon Gold 6248, g++ 13.3 -O2, old and new alternated for 8 rounds on one pinned core, the rows from 1000 bytes up agree in every round. A source offset by one byte gives the same numbers within 3%.
@nikosavola nikosavola closed this Oct 19, 2026
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.

1 participant