Getting per-thread CPU time on *BSD

Thomas Schatzl thomas.schatzl at oracle.com
Mon Jun 16 16:04:14 UTC 2025


Hi,

   thanks for looking into this.

On 16.06.25 16:21, Harald Eilertsen wrote:
> Hi again,
> 
> I think it should be possible to get what you need via the
> clock_gettime() call with the clock id returned by
> pthread_getcpuclockid() for the target thread.
> 
> https://urldefense.com/v3/__https://man.freebsd.org/cgi/man.cgi?query=clock_gettime__;!!ACWV5N9M2RV99hQ!Igm6XiYuRHoGdLiINNmnGjMmnpJb1YT9uiq9qJr4MmKjsNFtl7OTvu9ogF6zQHLj4oR_fedP1I3oOQDabcPm4dNT7XdIry9c$
> https://urldefense.com/v3/__https://man.freebsd.org/cgi/man.cgi?query=pthread_getcpuclockid__;!!ACWV5N9M2RV99hQ!Igm6XiYuRHoGdLiINNmnGjMmnpJb1YT9uiq9qJr4MmKjsNFtl7OTvu9ogF6zQHLj4oR_fedP1I3oOQDabcPm4dNT7dKHsMci$
> 
>  From what I can see these calls are also supported on OpenBSD and
> NetBSD.
> 

So this is somewhat similar to what linux does if both user and sys time 
are requested, getting a clock and then using that method? (I did not 
look into the linux code in detail).

When getting user time only, Linux seems to parse 
/proc/self/task/<pid>/stats or so file, not sure if that is possible on 
BSD too.

> One note, though: These calls return (afaict) the acumulated sys+user
> time of the thread in one timespec struct, not as separate sys+user
> times.
> 

That's fine for many cases, at least for GC we want both. Some users 
(JFR) seem to make the distinction, but I guess just returning the same 
value is better than the current implementation (crashing).

> If that's ok, I'm happy to try to implement it. Is there a test that can
> be used to check the implementation?
> 
jcmd <pid> Thread.print on a java process should print lines like:

"G1 Refine#3" os_prio=0 cpu=22.28ms elapsed=90.86s 
tid=0x0000f56fbc21f000 nid=0x75f4 runnable

The value after "cpu=" is derived from os::thread_cpu_time() (see 
Thread::print_on in thread.cpp) which seems to be unimplemented (just 
fail the VM) on *BSD.

I.e. os_bsd.cpp, search for "Unimplemented()" to find that above method.

Would be great to have support for that on non-OSX too so that we can 
rely on that.

Thanks,
   Thomas



More information about the bsd-port-dev mailing list