Search code examples
linuxtimesystemtime

More accurate equivalent for "time" command in Linux, regarding sys- and usertime?


I am in the following situation:

I want to determine the sys- and usertime of little snippets of (PHP- and C++) code. Obviously, I could use the "time" binary in Linux, but given the fact that these snippets run so fast, the normal (or even verbose) output of "time" wont suffice my purpose. The accuracy of "time" goes to milliseconds, while I need microseconds. Or even better: nanoseconds.

Can anyone point me to a piece of software that can do this for me? I found stuff for walltime, but it is sys- and usertime that I am interested at.

Thanks in advance!

BTW: Im running Ubuntu 10.10 64-bit


Solution

  • There is no method that's going to give you any equivalent of sys or usertime as reported by the time command that's going to be any more precise. Much of the apparent precision of the time command is false precision as it is.

    The technique for handling this is to put these snippets of code in tight loops that call them thousands of times and figuring out how long a given loop takes from that. And even then you should repeat the experiment a few times and pick the lowest time.

    Here's an analogy describing why the precision is false, and what I mean by that. Suppose you have someone using a stopwatch to time a race by manually hitting the button when the race started and when the person being timed crosses the finish line. Supposedly your stopwatch is accurate to the 100th of a second. But that precision is false because its dwarfed by the errors introduced by the reaction time of the person hitting the button.

    This is pretty closely analogous to why time gives you accuracy that's supposedly in microseconds, but is really significantly less precise. There is a lot going on in any given system at any given point in time, and all of those things introduce error into the calculations. The interrupts from network IO, or disk IO, the timer interrupts for running the scheduler, what other processes do to the L1 or L2 CPU cache. It all adds up.

    Using something like valgrind that runs your program on a simulated CPU can give you numbers that are seemingly accurate to the number of CPU cycles. But that precision isn't what you'll be experiencing in the real world. It's better to use the technique I originally described and just accept that these timings can be fuzzy.