crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.47k stars 1.62k forks source link

Port `Process.times` to RUsage? #7964

Closed jgaskins closed 5 years ago

jgaskins commented 5 years ago

While running Benchmark.measure on some code to see how much CPU time it consumes, I noticed it only reports with a granularity of 0.01 seconds. Because this code does I/O, this requires running it for a long time to get results with enough significant digits in it to be able to understand how it scales.

Ruby's Benchmark.measure offers microsecond precision, so I looked into Ruby's implementation of Process.times and I noticed they use LibC's getrusage API. I have an implementation of Process.times in Crystal I've been using locally to get those 4 orders of magnitude more precision, but I assume there was a reason Crystal doesn't use getrusage. I've found mentions of it as far back as Linux 2.6 (released 16 years ago) and it works fine on my Mac, so it probably has decent support.

I haven't posted a PR for it yet because I want to make sure there isn't a major blocker for it before I have to add LibC bindings into all of these:

aarch64-linux-gnu      i686-linux-gnu         x86_64-macosx-darwin
aarch64-linux-musl     i686-linux-musl        x86_64-openbsd
amd64-unknown-openbsd  x86_64-darwin          x86_64-portbld-freebsd
arm-linux-gnueabihf    x86_64-freebsd         x86_64-unknown-freebsd
i386-linux-gnu         x86_64-linux-gnu       x86_64-windows-msvc
i386-linux-musl        x86_64-linux-musl
asterite commented 5 years ago

I think when I implemented this (last commit in the line that calls times is on 2016) I checked Ruby's source code and they used the times C function. I think eventually Ruby optimized their code to get more precision but I didn't follow that evolution (last commit on the getrusage line is on 2017).

I think I looked into using getrusage but I wasn't sure it was going to work everywhere. If it does, then PR are most definitely welcome! In the worst case we can choose times or getrusage based on the system.

carlhoerberg commented 5 years ago

@jgaskins Post the PR :+1: