r/programming • • 12d ago

What it takes to count the Linux kernel's 36M lines of code in under 70ms

https://petros-papatheodorou.dev/writing/mezura/counting-the-linux-kernel/
264 Upvotes

29 comments sorted by

87

u/ArtOfWarfare 12d ago

I can’t tell why this is a problem someone wants solved in the first place?

107

u/petros211 12d ago

"This" being what? The line counting? Or knowing how much test code a codebase has, how many actual code lines it has compared to comments and blank lines, how many structs or classes it has, how much it grew since the last release, how much code the new PR brings in and what exactly this code is? Or the speed that means an editor extension can show updated numbers on every save without you knowing anything actually run, for any codebase in the world, or the fact that a gui that shows graphs and stats of a codebase so fast that it seems it didn't calculate nothing? Idk man I can think of many use cases

21

u/chucker23n 12d ago edited 12d ago

the speed that means an editor extension can show updated numbers on every save without you knowing anything actually run

Sure, but this kind of metric sounds more like something you'd do in CI. Push to a PR (yes, I know Linux doesn't use PRs), then generate a comment if line count has changed to a non-trivial extent.

Optimizations are always good, of course.

6

u/pauseless 10d ago

None of those use cases are that exciting. Anything PR related or reporting/graphing related that runs in less than a second is fine. Seems the original implementation was already at 0.4s? Even wanting to do it on every save in an editor, surely that can be async?

Why would one care about the entire Linux codebase on every save? One would normally work in a specific area.

Fwiw, this kind of rabbit hole is genuinely fun. I like optimising stuff and it’s great we can get here. I’m just struggling to think of the demand.

1

u/WindHawkeye 9d ago

All of those are completely pointless sorry

-14

u/bedrutton 12d ago

Lol you really didn't have to phrase this in such a passive-aggressive way

13

u/petros211 12d ago

Yeah well, when someone comes to the post to comment that a whole established domain + the new features and numbers that mezura brings in + the performance work and realizations of the article that could be useful to anyone, are all not useful and irrelevant, It's not me that started it :Ρ

20

u/archipeepees 12d ago edited 12d ago

sometimes it's ok to provide context with your links so that you can avoid foreseeable questions like "what is this?" and "why is this important?"

also, based on my experience with sentences, the "this" in the comment was probably referring to "counting the kernel's LoC in under 70ms".

0

u/petros211 11d ago

I thought the article itself explains that. Maybe I should have also added a short description here in the post, I will keep this in mind.

0

u/[deleted] 12d ago

[deleted] — view deleted comment

6

u/petros211 12d ago

It's not a genuine question. Happy to answer any question if it is well-intended.

4

u/ArtOfWarfare 12d ago

I feel your response is equally not genuine. You listed some hypothetical reasons. Is there an actual editor or pipeline or something where this code lives and runs being useful?

Did anyone file a bug report that other/older ways were too slow?

Who is opening the entire Linux source code and asking these questions and needing the answer in 70ms?

9

u/petros211 11d ago

Line counters already live inside real tools and pipelines.

- onefetch (the git summary CLI) uses tokei to compute language breakdowns and line counts.

- CI workflows run them for PR diff summaries, size/complexity info, and README badges.

- scc exports OpenMetrics, SQL, and CSV for Prometheus/Grafana dashboards and combines complexity with git churn for hotspot analysis.

- Mezura also has an mcp server so coding agents can check their own work.

- I am building a GUI version with more advanced visualizations and metrics, and mezura can count the Linux kernel before the first frame of the window is interactable, and also on every alt+tab and project change.

No there weren't any bug reports about the speed. When I got into the domain, scc and tokei were running the kernel in 470-500ms. Now scc runs in less than half the time, because we pushed each other and exchanged ideas and knowledge.

So the "bug" was that these tools were like 7 times slower than they could be. If this doesn't seem like a bug to you, and your reaction to the work that brings a tool's performance close to the hardware limit is to dismiss it as useless, then you are a major part of the problem of the enshitification of 99% of software today, so we ain't got nothing more to say.

9

u/IAmARougeAI 12d ago

It’s not even a question, it’s a statement with a question mark at the end.

2

u/ongrabbits 12d ago

I thought it was a good reply to somebody who doesn’t know

16

u/archipeepees 12d ago

all great software applications begin by counting lines of source code in under 70ms. didn't you know?

if you're wondering why 70ms is important, it's because 70% is a C in the American education system and Linux is written in C.

45

u/mark_99 12d ago edited 12d ago

Nice write up.

However this caught my eye, if I'm reading it right :

> Files of 256 KiB and larger are mapped with mmap, which cut wall time by 9% and page faults in half. Files modified in the last five seconds fall back to read, since truncating a mapped file mid-scan kills the process with SIGBUS.

I think I'd rather have it take a few more millis but not segfault if the files it's scanning are concurrently modified. Adding a heuristic check doesn't seem like the same thing as correct. It seems reasonable to say if the files are being modified the result might be slightly inaccurate, but maybe crashing doesn't seem ok.

21

u/petros211 12d ago

That's a good point, but the exact scope is pretty narrow, since:

  1. It only applies on Unix to files >= 256 KiB that haven't been modified in the last 5 seconds (the age check is specifically there to skip files actively being written or generated, like build outputs or redirects).
  2. A normal save by an editor or git writes a new file and renames it over the old path, which leaves the mapped inode untouched and does not trigger SIGBUS. You only hit SIGBUS if another process truncates a >= 256 KiB file *in place* during the few milliseconds it is mapped.

And also ripgrep's memory maps have the exact same "problem" and they document it similarly.

For a batch CLI counting static local source trees, 9% off total wall time and half the page faults was worth that tradeoff to me (similar to skipping extra syscalls on the read path that only matter on failing disks or FUSE direct_io mounts, which we talked through in https://github.com/subamanis/mezura/issues/16). That said, I get why someone scanning live mutating directories would want a flag to disable mmap, maybe I will provide one at some point.

3

u/mark_99 12d ago edited 12d ago

I'm not sure you're entirely correct about rg. I had a look and it only uses mmap for <= 10 explicit files. For the common case of a dir walk it's off by default (opt in with --mmap), whereas it's on in Mezura.

Also while edits and git will do temp-and-rename, truncate isn't that rare - shell redirects can do it, as can cp. I believe some editors write in place if they detect a symlink/hardlink.

You could add a SIGBUS handler and check if the address is within your mapped range, and retry with a regular read. You might need some shenanigans to map a new page in there so it can recover.

But copying rg (for real) seems simpler perhaps. Yeah you are going to lose a little perf in exchange for safety, but isn't that the Rust way?

1

u/petros211 12d ago

Ah yes it seems you are right, rg only enables mmap automatically for small explicit file lists..

On the crash vs. inaccurate count point though, I'm not sure silent wrong numbers are clearly better. Unlike grep, a line counter runs a stateful lexer. If an in-place write causes a torn read (half the old file, half the new one) and leaves a block comment or multiline string unclosed at the boundary, the rest of the file gets misclassified and the run exits 0 with corrupt counts. For a tool that feeds JSON reports, CI badges, and history logs, silently recording bogus numbers isn't great either.

That said, a SIGBUS crash with no error message is admittedly harsher than flagging the file as faulty. Making mmap opt-out is probably the cleaner middle ground, but I wouldn't make it opt-in.

11

u/pellets 12d ago

Counting lines for files that are changing seems like a losing battle.

> Adding a heuristic check doesn't seem like the same thing as correct.

I agree with this. Trying to be "correct" here could result in a never ending loop of finding where a heuristic isn't perfect and trying to make a better heuristic. Better to just count files the same regardless of when they were last updated. Maybe have an option to emit warnings if files are modified while counted. Or better, an option to lock a file while it's being counted.

7

u/mark_99 12d ago

A segfault is a very different category of error than an inaccurate/stale line count (which is perhaps to be tolerated if there's a write to the tree).

1

u/sbalogh3880 11d ago

A file lock only helps when writers cooperate with the same locking protocol; it cannot protect arbitrary files from in-place truncation.

2

u/pellets 11d ago

Even if it did work, it would be very unfriendly, since I'd expect the usual time someone wants lines counted, they wouldn't want such counting to cause their file edit to fail. There are workarounds like counting a snapshot.

1

u/petros211 11d ago

I am trying ro move away from snapshots, since today the --diff between git revisions does work with a snapshot (it copies the files of the revision to a temp folder with a worktree), but it's terrible, it takes 12 seconds to copy and almost 20 seconds to cleanup on windows, for the Linux tree. I am changing that to get only the changed files from git and count them without copying anything, but it's not great either it has many edge cases to handle and also if the diff is big, it's pretty slow too. I may end up writing a custom git object reader

For complete correctness though, I will provide a flag to turn memory mapping off, and also when it's on I will handle the case to not crash and report the file. Then at user space you can handle that appropriately, since the mezura lib target will report the faulty files and the user program can recount them or something

-104

u/pellets 12d ago

Interesting article in some ways, but needs a run through the LLM agent being told to make it more concise or something like that. Spend more time on the result and less time on the story of how the agent got there.

43

u/petros211 12d ago

The progression is kind of the point of the post. Showing the final design alone doesn't explain why flamegraphs and branch-miss counters pointed the wrong way, or why I needed a separate C baseline just to realize half the runtime was still my own architecture.

If someone only wants the final numbers, the summary table is right at the top.

-31

u/pellets 12d ago

There's plenty of differences between wanting to know "What it takes", "the final numbers", and the story of how someone learned "What it takes". From the title, I was expecting "What it takes". If you want it to be the story behind learning that, then that's fine, but it's not what I expected from the title.

8

u/petros211 12d ago edited 12d ago

Fair enough for the title I guess, but the article still explains what it takes, since the final parser architecture and its tricks are explained in the last chapter of the section about the parser. It be found from the table of contents right at the beginning of the article.