17 comments

  • ot14 hours ago
    You 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.<p>This is not well documented unfortunately, and I&#x27;m not aware of open-source implementations of this.<p>EDIT: Or maybe not, I&#x27;m not sure if PERF_COUNT_SW_TASK_CLOCK allows to select only user time. The kernel can definitely do it, but I don&#x27;t know if the wiring is there. However this definitely works for overall thread CPU time.
    • jerrinot14 hours ago
      That&#x27;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!
      • ot14 hours ago
        Yes you need some lazy setup in thread-local state to use this. And short-lived threads should be avoided anyway :)
        • catlifeonmars7 hours ago
          I guess if you need the concurrency&#x2F;throughput you should use a userspace green thread implementation. I’m guessing most implementations of green threads multiplex onto long running os threads anyway
          • jerrinot6 hours ago
            In 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.
    • nly6 hours ago
      Why do you need a seqlock? To make sure you&#x27;re not context switched out between the read of the page value and the rdtsc?<p>Presumably you mean you just double check the page value after the rdtsc to make sure it hasn&#x27;t changed and retry if it has?<p>Tbh I thought clock_gettime was a vdso based virtual syscall anyway
    • mgaunard36 minutes ago
      clock_gettime is not doing a syscall, it&#x27;s using vdso.
      • jerrinot8 minutes ago
        clock_gettime() goes through the vDSO shim, but whether it avoids a syscall depends on the clock ID and (in some cases) the clock source. For thread-specific CPU user time, the vDSO shim cannot resolve the request in user space and must transit into the kernel. In this specific case, there is absolutely a syscall.
  • shermantanktop13 hours ago
    Flamegraphs are wonderful.<p>Me: looks at my code. &quot;sure, ok, looks alright.&quot;<p>Me: looks at the resulting flamegraph. &quot;what the hell is this?!?!?&quot;<p>I&#x27;ve found all kinds of crazy stuff in codebases this way. Static initializers that aren&#x27;t static, one-line logger calls that trigger expensive serialization, heavy string-parsing calls that don&#x27;t memoize patterns, etc. Unfortunately some of those are my fault.
    • wging12 hours ago
      I also like icicle graphs for this. They&#x27;re flamegraphs, but aggregated in the reverse order. (I.e. if you have calls A-&gt;B-&gt;C and D-&gt;E-&gt;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&#x27;s wrong when you have a bunch of distinct codepaths that all invoke a common library where you&#x27;re spending too much time.)<p>Regular flamegraphs are good too, icicle graphs are just another tool in the toolbox.
      • pests8 hours ago
        So someone else linked the original flamegraph site [0] and it describes icicle graphs as &quot;inverting the y axis&quot; but that&#x27;s not only what&#x27;s happening, right? You bucket top-down the stack opposed to bottom-up, correct?<p>[0] <a href="https:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html" rel="nofollow">https:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html</a>
        • yxhuvud4 hours ago
          Right, what is needed is something trie-like, with the root being the most fine-grained call.
    • tempaccsoz511 hours ago
      Also cool that when you open it in a new tab, the svg [0] is interactive! You can zoom in by clicking on sections, and there&#x27;s a button to reset the zoom level.<p>[0]: <a href="https:&#x2F;&#x2F;questdb.com&#x2F;images&#x2F;blog&#x2F;2026-01-13&#x2F;before.svg" rel="nofollow">https:&#x2F;&#x2F;questdb.com&#x2F;images&#x2F;blog&#x2F;2026-01-13&#x2F;before.svg</a>
      • sllabres9 hours ago
        Yes, they are made with: <a href="http:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html" rel="nofollow">http:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html</a> and<p><a href="https:&#x2F;&#x2F;github.com&#x2F;brendangregg&#x2F;FlameGraph" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;brendangregg&#x2F;FlameGraph</a><p>Useful site if you are on to perf&#x2F;eBPF&#x2F;performance things with many examples and descriptions even for other uses as e.g. memory usage, disk usage (prefer heatmaps here but they are nice if you want to send someone a interactive view of their directory tree ...).
    • arethuza2 hours ago
      I always found profiling performance critical code and experimenting with optimisations to be one of the most enjoyable parts of development - probably because of the number of surprises that I encountered (&quot;Why on Earth is <i>that</i> so slow?&quot;).
    • jabwd12 hours ago
      I might be very wrong in every way but, string parsing and or manipulating and memoiziation... sound like a super strange combo? For the first you know you&#x27;re already doing expensive allocations, but the 2nd is also not a pattern I really see apart from in JS codebases. Could you provide more context on how this actually bit you in the behind? memoizing strings seems like a complicated and error prone &quot;welp it feels better now&quot; territory in my mind so I&#x27;m genuinely curious.
      • shermantanktop10 hours ago
        In Java it can be a bad toString() implementation hiding behind a + used for string assembly.<p>Or another great one: new instances of ObjectMapper created inside a method for a single call and then thrown away.
        • shermantanktop10 hours ago
          To be clear this is often sloppy code that shouldn’t have been written. But in a legacy codebase this stuff can easily happen.
      • tyingq12 hours ago
        &gt; but the 2nd is also not a pattern I really see apart from in JS codebases.<p>If you&#x27;re referring to &quot;one-line logger calls that trigger expensive serialization&quot;, it&#x27;s also common in java.
    • sroerick11 hours ago
      I&#x27;ve never used flamegraphs but would like to know about them. Can you explain more? Or where should I start?
      • atdt11 hours ago
        Flame graphs have an official web site, maintained by Brendan Gregg, who invented them: <a href="https:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html" rel="nofollow">https:&#x2F;&#x2F;www.brendangregg.com&#x2F;flamegraphs.html</a>. It&#x27;s a useful starting point.
      • jsymolon3 hours ago
        I use them all the time on Perl code.<p><a href="https:&#x2F;&#x2F;metacpan.org&#x2F;pod&#x2F;Devel::NYTProf" rel="nofollow">https:&#x2F;&#x2F;metacpan.org&#x2F;pod&#x2F;Devel::NYTProf</a>
      • dummydummy12345 hours ago
        I would also try hotspot, it is a interactive viewer for perf graphs.
  • jerrinot16 hours ago
    Author 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 &quot;What is the CPU time of this thread?&quot; is&#x2F;was a much more expensive question than it should be.
    • jacquesm15 hours ago
      I don&#x27;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.
      • rcxdude15 hours ago
        Stability 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&#x27;re talking about nanoseconds across a long time period, seconds or longer, then yeah, you probably should care about your clock. But when you&#x27;re measuring nanoseconds out of a millisecond or microsecond, it really doesn&#x27;t matter that much and you&#x27;re going to be OK with the average crystal oscillator in a PC. (and if you&#x27;re measuring a 10% difference like in the article, you&#x27;re going to be fine with a mechanical clock as your reference if you can do the operation a billion times in a row).
        • jacquesm14 hours ago
          This 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.
          • loeg11 hours ago
            For 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.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;facebook&#x2F;folly&#x2F;blob&#x2F;main&#x2F;folly&#x2F;docs&#x2F;Benchmark.md#a-look-under-the-hood" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;facebook&#x2F;folly&#x2F;blob&#x2F;main&#x2F;folly&#x2F;docs&#x2F;Bench...</a>
            • jacquesm11 hours ago
              You don&#x27;t actually know that for sure. You have only placed a new upper bound.
              • loeg9 hours ago
                This seems like more of a philosophical argument than a practical one.
                • jacquesm3 hours ago
                  No, it is a very practical one and I&#x27;m actually surprised that you don&#x27;t see it that way. Benchmarking is hard, and if you don&#x27;t understand the basics then you can easily measure nonsense.
                  • jerrinot2 hours ago
                    You 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.<p>The mean does get proper statistical treatment (t-distribution confidence interval), but you&#x27;re right that JMH doesn&#x27;t compute confidence intervals for percentiles. Reporting p0.00 with three significant figures is ... optimistic.<p>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.
    • Neywiny15 hours ago
      Did you look into the large spread on your distributions? Some of these span multiple orders of magnitude which is interesting
      • jerrinot15 hours ago
        Fair point. These were run on a standard dev workstation under load, which may account for the noise. I haven&#x27;t done a deep dive into the outliers yet, but the distribution definitely warrants a more isolated look.
    • 6r1714 hours ago
      Very thankful for the 1liner tldr<p>edit : I had an afterthought about this because it ended up being a low quality comment ;<p>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 -<p>reading this short form felt like that cool friend who gave you a heads up.
      • jerrinot14 hours ago
        I was unsure whether to post it or not so I am glad you found it useful!
        • 6r1714 hours ago
          I 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&#x27;s not the same kind of content I don&#x27;t bother with it.It really feels like &quot;here is the stuff, here&#x27;s more about it if you want to&quot; - really really appreciate that form and will definitely do the same format myself
    • abicklefitch11 hours ago
      Quelle Suprise
  • furyofantares13 hours ago
    &gt; Flame graph image<p>&gt; Click to zoom, open in a new tab for interactivity<p>I admit I did not expect &quot;Open Image in New Tab&quot; to do what it said on the tin. I guess I was aware that it was possible with SVG but I don&#x27;t think I&#x27;ve ever seen it done and was really not expecting it.
    • jerrinot13 hours ago
      Courtesy of Brendan Gregg and his flamegraph.pl scripts: <a href="https:&#x2F;&#x2F;github.com&#x2F;brendangregg&#x2F;FlameGraph" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;brendangregg&#x2F;FlameGraph</a><p>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.
  • mgaunard37 minutes ago
    Obviously 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.
  • jonasn6 hours ago
    Author of the OpenJDK patch here.<p>Thanks for the write-up Jaromir :) For those interested, I explored memory overhead when reading &#x2F;proc—including eBPF profiling and the history behind the poorly documented user-space ABI.<p>Full details in my write-up: <a href="https:&#x2F;&#x2F;norlinder.nu&#x2F;posts&#x2F;User-CPU-Time-JVM&#x2F;" rel="nofollow">https:&#x2F;&#x2F;norlinder.nu&#x2F;posts&#x2F;User-CPU-Time-JVM&#x2F;</a>
    • jerrinot6 hours ago
      Hi Jonas, thanks for the work on OpenJDK and the post! I swear I hadn&#x27;t seen your blog :) I finished my draft around Christmas and it’s been in the queue since. Great minds think alike, I guess.<p>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.<p>edit2: I linked your article from my post.
  • pjmlp7 hours ago
    Which goes to show writing C, C++ or whatever systems language isn&#x27;t automatically blazing fast, depending on what is being done.<p>Very interesting read.
  • higherhalf14 hours ago
    clock_gettime() goes through vDSO, avoiding a context switch. It shows up on the flamegraph as well.
    • jerrinot14 hours ago
      Only for some clocks (CLOCK_MONOTONIC, etc) and some clock sources. For VIRT&#x2F;SCHED, the vDSO shim still has to invoke the actual syscall. You can&#x27;t avoid the kernel transition when you need per-thread accounting.
      • touisteur7 hours ago
        Oh for some time after its introduction, CLOCK_MONOTONIC_RAW wasn&#x27;t vDSO&#x27;d and it took some time and syscall profiling (&#x27;huh, why do I see these as syscalls in perf record -e syscalls&#x27; ...) to understand what was going on.
      • higherhalf13 hours ago
        Thanks, I really should&#x27;ve looked deeper than that.
        • jerrinot13 hours ago
          no problem at all, I was confused too when I saw the profile for the first time.
    • ot14 hours ago
      If you look below the vDSO frame, there is still a syscall. I think that the vDSO implementation is missing a fast path for this particular clock id (it could be implemented though).
    • a-dub14 hours ago
      edit: 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.<p>here it gets the task struct: <a href="https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;time&#x2F;posix-cpu-timers.c#L358" rel="nofollow">https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;time&#x2F;...</a> and here <a href="https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;time&#x2F;posix-cpu-timers.c#L194" rel="nofollow">https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;time&#x2F;...</a> to here where it actually pulls the value out: <a href="https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;sched&#x2F;cputime.c#L844" rel="nofollow">https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;kernel&#x2F;sched...</a><p>where here is the vdso clock pick logic <a href="https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;lib&#x2F;vdso&#x2F;gettimeofday.c#L288" rel="nofollow">https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;lib&#x2F;vdso&#x2F;get...</a> and here is the fallback to the syscall if it&#x27;s not a vdso clock <a href="https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;lib&#x2F;vdso&#x2F;gettimeofday.c#L317" rel="nofollow">https:&#x2F;&#x2F;elixir.bootlin.com&#x2F;linux&#x2F;v6.18.5&#x2F;source&#x2F;lib&#x2F;vdso&#x2F;get...</a>
  • Ono-Sendai6 hours ago
    &quot;look, I&#x27;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&quot;<p><a href="https:&#x2F;&#x2F;x.com&#x2F;rygorous&#x2F;status&#x2F;1271296834439282690" rel="nofollow">https:&#x2F;&#x2F;x.com&#x2F;rygorous&#x2F;status&#x2F;1271296834439282690</a>
  • goodroot13 hours ago
    The QuestDB team are among the best doing it.<p>Love the people and their software.<p>Great blog Jaromir!
  • amelius5 hours ago
    It&#x27;s kinda crazy the amount of plumbing required to get a few bits across the CPU.
  • ee99ee15 hours ago
    This is such a great writeup
  • otterley12 hours ago
    It 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.
    • loeg11 hours ago
      400x slower than 70ns is still only 28us. How often is the JVM calling this function?
      • otterley9 hours ago
        It 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.<p>This is what flame graphs are super helpful for, to see whether it’s really a problem or not.<p>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.
        • loeg8 hours ago
          If it&#x27;s calling it twice per function, that&#x27;s enormously expensive and this is a major win.
      • u80802 hours ago
        28us is still solid amount of time
  • burnt-resistor2 hours ago
    I really wished™ there was an API&#x2F;ABI for userland- and kernelland-defined individual virtual files at arbitrary locations, backed by processes and kernel modules respectively. I&#x27;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&#x27;s often no need to have an actual file on any media or the expense of IOPS.<p>While I don&#x27;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&#x2F;API&#x2F;ABI.
  • xthe13 hours ago
    This is a great example of how a small change in the right place can outweigh years of incremental tuning.
    • nomel13 hours ago
      I don&#x27;t think I&#x27;ve ever seen less than 10x speedup after putting some effort into improving performance of &quot;organic&quot;&#x2F;legacy code. It&#x27;s always <i>shocking</i> how slow code can be before anyone complains.
  • squirrellous9 hours ago
    Does 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.
  • tomiezhang9 hours ago
    cool