Skip to content

gh-137627: Make csv.Sniffer.sniff() delimiter detection 1.6x faster - #137628

Merged
hugovk merged 31 commits into
python:mainfrom
maurycy:csv-sniffer-counter-set
Oct 23, 2025
Merged

hugovk merged 31 commits into
python:mainfrom
maurycy:csv-sniffer-counter-set

Conversation

@maurycy

@maurycy maurycy commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor

The basic idea is not to iterate over all ASCII characters and count their frequency on each line in _guess_delimiter but only over present characters, and just backfill zeros.

Benchmark

There is no csv.Sniffer benchmark in pyperformance, so I created a simple benchmark instead:

import csv, pathlib, pyperf
def sniff(s): csv.Sniffer()._guess_delimiter(s, None)
r = pyperf.Runner()
sizes = [1024, 2048, 4096]
for file in pathlib.Path("/home/maurycy/CSVsniffer/CSV/").glob("*.csv"):
    for s in sizes:
        with file.open() as f:
            try:
                r.bench_func(f"csv_sniff({file.name}, {s})", sniff, f.read(s))
            except UnicodeDecodeError:
                pass

using all 149 files from CSVSniffer (MIT License), reading only the sample, as recommended in docs.python.org example. That's what real users do, too. Unfortunately, it takes a few hours to run.

The result:

Geometric mean: 1.60x faster

The full results (compare_to --table --table-format=md, and JSON files):

Correctness

I created a simple script to confirm that the output of Sniffer()._guess_delimiter() did not change. It uses ~1100 CSV files from the CSVSniffer project (MIT License).

The script:
from pathlib import Path

import csv_96b7a2eba423b42320f15fd4974740e3e930bb8b as csv_original
import csv as csv_modified

# https://github.com/ws-garcia/CSVsniffer
CSV_DIR_PATH = Path("/home/maurycy/CSVsniffer/")
SAMPLE = 1024

csv_files = list(CSV_DIR_PATH.rglob("*.[cC][sS][vV]"))


def differ(path, original, modified):
    with open(path, "r", encoding="utf-8", errors="ignore") as f:
        data = f.read(SAMPLE)
        return original(data) != modified(data)


original_guess_delimiter = (
    lambda data: csv_original.Sniffer()._guess_delimiter(data, delimiters=None)
)
modified_guess_delimiter = (
    lambda data: csv_modified.Sniffer()._guess_delimiter(data, delimiters=None)
)

differences, total = (
    sum(
        differ(path, original_guess_delimiter, modified_guess_delimiter)
        for path in csv_files
    ),
    len(csv_files),
)
print(f"{total} CSV files in '{CSV_DIR_PATH}', {differences} differences.")

where Lib/csv_96b7a2eba423b42320f15fd4974740e3e930bb8b.py is https://github.com/python/cpython/blob/96b7a2eba423b42320f15fd4974740e3e930bb8b/Lib/csv.py from the main branch, and:

% git rev-parse HEAD
8614756ea48060aa8c4d4c1508b0221e1b50d263
% git status
## csv-sniffer-counter-set...origin/csv-sniffer-counter-set
?? Lib/csv_96b7a2eba423b42320f15fd4974740e3e930bb8b.py
?? csv-sniffer-diff.py

The result:

% ./python csv-sniffer-diff.py
1118 CSV files in '/home/maurycy/CSVsniffer/', 0 differences.

Environment

% ./python -c "import sysconfig; print(sysconfig.get_config_var('CONFIG_ARGS'))"
'--with-lto' '--enable-optimizations'

sudo ./python -m pyperf system tune ensured.

Notes

  • The optimization is in csv.Sniffer()._read_delimiter() which runs only if regular expressions in csv.Sniffer()._guess_quote_and_delimiter() failed, so there's no guarantee that csv.Sniffer().sniff() will always be faster
  • My original patch relied on confusing set operations.
@maurycy maurycy changed the title gh-137627: Make csv.Sniffer._guess_delimiter() 2x faster Aug 11, 2025
Comment thread Lib/csv.py Resolved
@maurycy
maurycy requested a review from AA-Turner August 11, 2025 05:37

@picnixz picnixz left a comment

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.

Are the benchmarks done with a POG+LTO build?

Comment thread Lib/csv.py Resolved

@AA-Turner AA-Turner left a comment •

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'm not a CSV expert, but here is a cursory review of the set logic. You should provide a (range of) benchmarks to back up the claim that it is twice as fast, though, ideally using pyperformance.

Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
@maurycy

maurycy commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor Author

@picnixz @AA-Turner I really appreciate your feedback! It's great. I will provide more benchmarks, including with enabled optimizations and ideally with pyperformance, rephrase NEWS, and add in a whatsnew.

@picnixz

picnixz commented Aug 12, 2025

Copy link
Copy Markdown
Member

Benchmarks without optimizations are not relevant so just run those with.

@maurycy maurycy changed the title gh-137627: Make csv.Sniffer.sniff() 2x faster Aug 13, 2025
@maurycy

maurycy commented Aug 13, 2025 •

Copy link
Copy Markdown
Contributor Author

@picnixz @AA-Turner @ZeroIntensity

Thank you for all the comments:

  • I created a much more rigorous benchmark than before, see the results: https://github.com/maurycy/cpython-test/tree/main/csv-sniffer-counter-set The benchmark is now on par with how people use the class.
  • I've changed the approach, ditching confusing set operations. The speed up now comes mostly from not iterating over ascii over and over, and more efficient zero backfilling.
  • There is nothing about csv.Sniffer() in pyperformance, so I was a bit stuck here.
  • I updated the docs.
Comment thread Doc/whatsnew/3.15.rst Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
maurycy and others added 2 commits August 18, 2025 20:38
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
@maurycy

maurycy commented Aug 19, 2025 •

Copy link
Copy Markdown
Contributor Author

@picnixz

Thank you for your yesterday's review:

  • I renamed the variables and simplified the zero-bucket, as per your suggestion,
  • I added the tests for the tie break (insert v. append of the zero bucket) to confirm that the behavior has not changed,
  • I updated the docs and the benchmark (it's now 1.6x faster!)

Thank you!

@maurycy
maurycy requested a review from picnixz August 19, 2025 10:49
@ZeroIntensity

Copy link
Copy Markdown
Member

Love the enthusiasm, but please try to avoid continuously rebasing (pressing "update branch"). It wastes CI time and also puts a ding in all of our inboxes. Updating the branch should generally only be done to resolve merge conflicts.

@maurycy

maurycy commented Aug 24, 2025 •

Copy link
Copy Markdown
Contributor Author

FYI: I created a simple check ensuring that the output of csv.Sniffer()._guess_delimiter() did not change:

@picnixz picnixz left a comment

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.

Overall, looks good but please add a test with corner cases when the guessing algorithm makes multiple rounds.

Comment thread Lib/test/test_csv.py Resolved
Comment thread Lib/test/test_csv.py Resolved
Comment thread Lib/test/test_csv.py Resolved
maurycy and others added 2 commits August 28, 2025 17:11
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Comment thread Doc/whatsnew/3.15.rst Resolved
Comment thread Lib/csv.py Resolved
maurycy and others added 4 commits August 28, 2025 17:24
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Comment thread Lib/test/test_csv.py Resolved
Comment thread Lib/test/test_csv.py Resolved
Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>

@picnixz picnixz left a comment

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.

This looks fine to me but I want another core dev to have a look just in case I missed some obvious things (maybe @serhiy-storchaka?)

@maurycy

maurycy commented Sep 8, 2025 •

Copy link
Copy Markdown
Contributor Author

@ZeroIntensity @AA-Turner What do you think about this PR now?

@hugovk hugovk left a comment

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.

Thanks!

Comment thread Lib/csv.py Resolved
Comment thread Lib/csv.py Resolved
@hugovk
hugovk merged commit 6be6f8f into python:main Oct 23, 2025
@hugovk

hugovk commented Oct 23, 2025

Copy link
Copy Markdown
Member

Thanks!

@maurycy
maurycy deleted the csv-sniffer-counter-set branch October 23, 2025 13:13
@bedevere-bot

Copy link
Copy Markdown

⚠️⚠️⚠️ Buildbot failure ⚠️⚠️⚠️

Hi! The buildbot AMD64 Windows11 Bigmem 3.x (tier-1) has failed when building commit 6be6f8f.

What do you need to do:

  1. Don't panic.
  2. Check the buildbot page in the devguide if you don't know what the buildbots are or how they work.
  3. Go to the page of the buildbot that failed (https://buildbot.python.org/#/builders/1079/builds/7354) and take a look at the build logs.
  4. Check if the failure is related to this commit (6be6f8f) or if it is a false positive.
  5. If the failure is related to this commit, please, reflect that on the issue and make a new Pull Request with a fix.

You can take a look at the buildbot page here:

https://buildbot.python.org/#/builders/1079/builds/7354

Failed tests:

  • test_zipimport

Failed subtests:

  • testZip64LargeFile - test.test_zipimport.UncompressedZipImportTestCase.testZip64LargeFile
  • testZip64LargeFile - test.test_zipimport.ZStdCompressedZipImportTestCase.testZip64LargeFile
  • testZip64LargeFile - test.test_zipimport.DeflateCompressedZipImportTestCase.testZip64LargeFile

Summary of the results of the build (if available):

==

Click to see traceback logs
Traceback (most recent call last):
  File "R:\buildarea\3.x.ambv-bb-win11.bigmem\build\Lib\test\test_zipimport.py", line 934, in testZip64LargeFile
    with open(os_helper.TESTFN, "wb") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 28] No space left on device


Traceback (test.test_zipimport.DeflateCompressedZipImportTestCase.testTraceback) ... ok


Traceback (test.test_zipimport.UncompressedZipImportTestCase.testTraceback) ... ok


Traceback (most recent call last):
  File "R:\buildarea\3.x.ambv-bb-win11.bigmem\build\Lib\test\test_zipimport.py", line 997, in testZip64LargeFile
    with open(TEMP_ZIP, "wb") as f:
         ~~~~^^^^^^^^^^^^^^^^
OSError: [Errno 28] No space left on device


Traceback (most recent call last):
  File "R:\buildarea\3.x.ambv-bb-win11.bigmem\build\Lib\test\test_zipimport.py", line 1000, in testZip64LargeFile
    f.seek(offset, os.SEEK_SET)
    ~~~~~~^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 28] No space left on device


Traceback (test.test_zipimport.ZStdCompressedZipImportTestCase.testTraceback) ... ok
@hugovk

hugovk commented Oct 23, 2025

Copy link
Copy Markdown
Member

Buildbot failure unrelated: "OSError: [Errno 28] No space left on device".

I'll inform the owner.

StanFromIreland pushed a commit to StanFromIreland/cpython that referenced this pull request Dec 6, 2025
…faster (python#137628)

Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

6 participants