6 ms·
A 40-line fix eliminated a 400x performance gap
- jerrinot 9mo agoAuthor here. After my last post about kernel bugs, I spent some time looking at how the JVM reports its own thread activity. It turns out that "What is the CPU time of this thread?" is/was a much more expensive question than it should be.
- Neywiny 9mo agoDid you look into the large spread on your distributions? Some of these span multiple orders of magnitude which is interesting
- jerrinot 9mo agoFair point. These were run on a standard dev workstation under load, which may account for the noise. I haven't done a deep dive into the outliers yet, but the distribution definitely warrants a more isolated look.
- jacquesm 9mo agoI don't think it is possible to talk about fractions of nanoseconds without having an extremely good idea of the stability and accuracy of your clock. At best I think you could claim there is some kind of reduction but it is super hard to make such claims in the absolute without doing a massive amount of prep work to ensure that the measured times themselves are indeed accurate. You could be off by a large fraction and never know the difference. So unless there is a hidden atomic clock involved somewhere in these measurements I think they should be qualified somehow.
- rcxdude 9mo agoStability and accuracy, when applied to clocks, are generally about dynamic range, i.e. how good is the scale with which you are measuring time. So if you're talking about nanoseconds across a long time period, seconds or longer, then yeah, you probably should care about your clock. But when you're measuring nanoseconds out of a millisecond or microsecond, it really doesn't matter that much and you're going to be OK with the average crystal oscillator in a PC. (and if you're measuring a 10% difference like in the article, you're going to be fine with a mechanical clock as your reference if you can do the operation a billion times in a row).
- jacquesm 9mo agoThis setup is a user space program on a machine that is not exclusively dedicated to the test running all kinds of interrupts (and other tasks) left, right and center through the software under test.
- loeg 9mo agoFor something like this, you can just take several trials and look at the minimum observed time, which is when there will have been ~no interruptions. https://github.com/facebook/folly/blob/main/folly/docs/Benchmark.md#a-look-under-the-hood https://github.com/facebook/folly/blob/main/folly/docs/Bench...
- jacquesm 9mo agoYou don't actually know that for sure. You have only placed a new upper bound.
- loeg 9mo agoThis seems like more of a philosophical argument than a practical one.
- jacquesm 9mo agoNo, it is a very practical one and I'm actually surprised that you don't see it that way. Benchmarking is hard, and if you don't understand the basics then you can easily measure nonsense.
- jerrinot 9mo agoYou raise a fair point about the percentiles. Those are reported as point estimates without confidence intervals and the implied precision overstates what system clock can deliver. The mean does get proper statistical treatment (t-distribution confidence interval), but you're right that JMH doesn't compute confidence intervals for percentiles. Reporting p0.00 with three significant figures is ... optimistic. That said I think the core finding survives this critique. The improvement shows up consistently across ~11 million samples at every percentile from p0.50 through p0.999.
- 6r17 9mo agoVery thankful for the 1liner tldr edit : I had an afterthought about this because it ended up being a low quality comment ; Bringing up such TLDR give a lot of value to reading content, especially on HN, as it provides way more inertia and let focus on - reading this short form felt like that cool friend who gave you a heads up.
- jerrinot 9mo agoI was unsure whether to post it or not so I am glad you found it useful!
- 6r17 9mo agoI have that 10-30s time window to fill when claude might be loading some stuff ; the 1 liner is exactly what fits in that window - it makes me wonder about the original idea of twitter now that I think of it - but since it's not the same kind of content I don't bother with it.It really feels like "here is the stuff, here's more about it if you want to" - really really appreciate that form and will definitely do the same format myself
- abicklefitch 9mo ago[dead]
- ee99ee 9mo agoThis is such a great writeup
- higherhalf 9mo agoclock_gettime() goes through vDSO, avoiding a context switch. It shows up on the flamegraph as well.
- a-dub 9mo agoedit: agh, no. CLOCK_THREAD_CPUTIME_ID falls through the vdso to the kernel which makes sense as it would likely need to look at the task struct. here it gets the task struct: https://elixir.bootlin.com/linux/v6.18.5/source/kernel/time/posix-cpu-timers.c#L358 https://elixir.bootlin.com/linux/v6.18.5/source/kernel/time/... and here https://elixir.bootlin.com/linux/v6.18.5/source/kernel/time/posix-cpu-timers.c#L194 https://elixir.bootlin.com/linux/v6.18.5/source/kernel/time/... to here where it actually pulls the value out: https://elixir.bootlin.com/linux/v6.18.5/source/kernel/sched/cputime.c#L844 https://elixir.bootlin.com/linux/v6.18.5/source/kernel/sched... where here is the vdso clock pick logic https://elixir.bootlin.com/linux/v6.18.5/source/lib/vdso/gettimeofday.c#L288 https://elixir.bootlin.com/linux/v6.18.5/source/lib/vdso/get... and here is the fallback to the syscall if it's not a vdso clock https://elixir.bootlin.com/linux/v6.18.5/source/lib/vdso/gettimeofday.c#L317 https://elixir.bootlin.com/linux/v6.18.5/source/lib/vdso/get...
- jerrinot 9mo agoOnly for some clocks (CLOCK_MONOTONIC, etc) and some clock sources. For VIRT/SCHED, the vDSO shim still has to invoke the actual syscall. You can't avoid the kernel transition when you need per-thread accounting.
- higherhalf 9mo agoThanks, I really should've looked deeper than that.
- jerrinot 9mo agono problem at all, I was confused too when I saw the profile for the first time.
- touisteur 9mo ago
- ot 9mo agoYou can do even faster, about 8ns (almost an additional 10x improvement) by using software perf events: PERF_COUNT_SW_TASK_CLOCK is thread CPU time, it can be read through a shared page (so no syscall, see perf_event_mmap_page), and then you add the delta since the last context switch with a single rdtsc call within a seqlock. This is not well documented unfortunately, and I'm not aware of open-source implementations of this. EDIT: Or maybe not, I'm not sure if PERF_COUNT_SW_TASK_CLOCK allows to select only user time. The kernel can definitely do it, but I don't know if the wiring is there. However this definitely works for overall thread CPU time.
- jerrinot 9mo agoThat's a brilliant trick. The setup overhead and permission requirements for perf_event might be heavy for arbitrary threads, but for long-lived threads it looks pretty awesome! Thanks for sharing!
- ot 9mo agoYes you need some lazy setup in thread-local state to use this. And short-lived threads should be avoided anyway :)
- catlifeonmars 9mo agoI guess if you need the concurrency/throughput you should use a userspace green thread implementation. I’m guessing most implementations of green threads multiplex onto long running os threads anyway
- jerrinot 9mo agoIn a system with green threads, you typically want the CPU time of the fiber or tasklet rather than the carrier thread. In that case, you have to ask the scheduler, not the kernel.
- deleted 9mo ago[deleted]
- goodroot 9mo agoThe QuestDB team are among the best doing it. Love the people and their software. Great blog Jaromir!
- furyofantares 9mo ago> Flame graph image > Click to zoom, open in a new tab for interactivity I admit I did not expect "Open Image in New Tab" to do what it said on the tin. I guess I was aware that it was possible with SVG but I don't think I've ever seen it done and was really not expecting it.
- jerrinot 9mo agoCourtesy of Brendan Gregg and his flamegraph.pl scripts: https://github.com/brendangregg/FlameGraph https://github.com/brendangregg/FlameGraph Normally, I use the generator included in async-profiler. It produces interactive HTML. But for this post, I used Brendan’s tool specifically to have a single, interactive SVG.
- IshKebab 9mo agoNote that pprof produces much fancier interactive flame graphs. I'm not sure they're a single SVG though. Also `samply` and the Firefox profiler are pretty fancy too. There's really no reason to use the original flamegraph scripts.
- xthe 9mo agoThis is a great example of how a small change in the right place can outweigh years of incremental tuning.
- nomel 9mo agoI don't think I've ever seen less than 10x speedup after putting some effort into improving performance of "organic"/legacy code. It's always shocking how slow code can be before anyone complains.
- shermantanktop 9mo agoFlamegraphs are wonderful. Me: looks at my code. "sure, ok, looks alright." Me: looks at the resulting flamegraph. "what the hell is this?!?!?" I've found all kinds of crazy stuff in codebases this way. Static initializers that aren't static, one-line logger calls that trigger expensive serialization, heavy string-parsing calls that don't memoize patterns, etc. Unfortunately some of those are my fault.
- wging 9mo agoI also like icicle graphs for this. They're flamegraphs, but aggregated in the reverse order. (I.e. if you have calls A->B->C and D->E->C, then both calls to C are aggregated together, rather than being stacked on top of B and E respectively. It can make it easier to see what's wrong when you have a bunch of distinct codepaths that all invoke a common library where you're spending too much time.) Regular flamegraphs are good too, icicle graphs are just another tool in the toolbox.
- pests 9mo agoSo someone else linked the original flamegraph site [0] and it describes icicle graphs as "inverting the y axis" but that's not only what's happening, right? You bucket top-down the stack opposed to bottom-up, correct? [0] https://www.brendangregg.com/flamegraphs.html https://www.brendangregg.com/flamegraphs.html
- yxhuvud 9mo agoRight, what is needed is something trie-like, with the root being the most fine-grained call.
- wging 9mo agoIt's certainly possible that what I encountered, labeled as an 'icicle graph', is a nonstandard usage of the term. But if so, that's a shame. I don't think inverting the y-axis is useful by itself, the different bucketing is what makes for an actually useful change.
- 9mo ago
- otterley 9mo agoIt took seven years to address this concern following the initial bug report (2018). That seems like a lot, considering how instrumenting CPU time can be in the hot path for profiled code.
- loeg 9mo ago400x slower than 70ns is still only 28us. How often is the JVM calling this function?
- otterley 9mo agoIt depends. If you’re doing continuous profiling, it’d make a call to get the current time at every method entry and exit, each of which could then add a context switch. In an absolute sense it appears to be small, but it could really add up. This is what flame graphs are super helpful for, to see whether it’s really a problem or not. Also, remember that every extra moment running instructions is a lost opportunity to put the CPU to sleep, so this has energy efficiency impact as well.
- loeg 9mo agoIf it's calling it twice per function, that's enormously expensive and this is a major win.
- singron 9mo agoIf you are doing continuous profiling, you are probably using a low overhead stack sampling profiler rather than recording every method entry and exit.
- otterley 9mo agoThat's a fair point. It really depends. For example, if you're recording method run times via an observability SDK at full fidelity, this could be an issue.
- u8080 9mo ago
- squirrellous 9mo agoDoes anyone knowledgeable know whether it’s possible to drastically reduce the overhead of reading from procfs? IIUC everything in it is in-memory, so there’s no real reason reading some data should take the order of 10us.
- tomiezhang 9mo agocool
- pjmlp 9mo agoWhich goes to show writing C, C++ or whatever systems language isn't automatically blazing fast, depending on what is being done. Very interesting read.
- Ono-Sendai 9mo ago"look, I'm sorry, but the rule is simple: if you made something 2x faster, you might have done something smart if you made something 100x faster, you definitely just stopped doing something stupid" https://x.com/rygorous/status/1271296834439282690 https://x.com/rygorous/status/1271296834439282690
- jonasn 9mo agoAuthor of the OpenJDK patch here. Thanks for the write-up Jaromir :) For those interested, I explored memory overhead when reading /proc—including eBPF profiling and the history behind the poorly documented user-space ABI. Full details in my write-up: https://norlinder.nu/posts/User-CPU-Time-JVM/ https://norlinder.nu/posts/User-CPU-Time-JVM/
- jerrinot 9mo agoHi Jonas, thanks for the work on OpenJDK and the post! I swear I hadn't seen your blog :) I finished my draft around Christmas and it’s been in the queue since. Great minds think alike, I guess. edit: I just read your blog in full and I have to say I like it more than mine. You put a lot more rigor into it. I’m just peeking into things. edit2: I linked your article from my post.
- jonasn 9mo agoThanks for the kind words and the link :).
- kstrauser 9mo agoWhy do you suppose it was originally written the way it was? To my eyes, that seems like a horrible approach. Doing file IO and parsing strings in every call? What?! And yet I assume the original author was a smart person who had a reason why this made sense to them, and my inability to guess why is my own limitation and not theirs. So, why do you reckon they did that?
- jonasn 9mo agoYou are spot on that the original author had a valid reason: at the time, it was literally the only way to do it. The method in question (Java 1.5) was released in September 2004. While the POSIX standard existed, it only provided a way to get total CPU time, not the specific user time that Java needed. You can read about it more in the history section here: https://norlinder.nu/posts/User-CPU-Time-JVM/#a-walk-through-history https://norlinder.nu/posts/User-CPU-Time-JVM/#a-walk-through.... But it's worth noting that while this specific case can be "fixed" with a function call, parsing /proc is still the standard way to get data in Linux. Even today, a vast amount of kernel telemetry is only exposed via the filesystem. If you look at the source code for tools like htop, they are still busy parsing text files from /proc to get memory stats (/proc/meminfo), network I/O, or per-process limits. See here https://github.com/hishamhm/htop/blob/master/linux/LinuxProcessList.c https://github.com/hishamhm/htop/blob/master/linux/LinuxProc....
- amelius 9mo agoIt's kinda crazy the amount of plumbing required to get a few bits across the CPU.
- burnt-resistor 9mo agoI really wished™ there was an API/ABI for userland- and kernelland-defined individual virtual files at arbitrary locations, backed by processes and kernel modules respectively. I've tried pipes, overlays, and FUSE to no avail. It would greatly simply configuration management implementations while maintaining compatibility with the convention of plain text files, and there's often no need to have an actual file on any media or the expense of IOPS. While I don't particularly like the IO overhead and churn consequences of real files for performance metrics, I get the 9p-like appeal of treating the virtual fs as a DBMS/API/ABI.
- mgaunard 9mo agoObviously a vdso read is going to be significantly faster than a syscall switching to the kernel, writing serialized data to a buffer, switching back to userland, and parsing that data.