5 Answers
5

Where $$ is the PID of the process you want to check. This will return the elapsed time in the format [[dd-]hh:]mm:ss. Or, with newer versions of the procps-ng tool suite, use ps -p $$ -o etimes= (with an added s) to get time formatted just as seconds, which is more useful in scripts.

The ps program gets this from /proc/$$/stat, where one of the fields (see man proc) is process start time. This is, unfortunately, specified to be the time in jiffies (an arbitrary time counter used in the Linux kernel) since the system boot. So you have to determine the time at which the system booted (from /proc/stat), the number of jiffies per second on this system (which turns out to be hard to determine, although some safe guesses can be made as long as you're not worried about keeping it working in the future), and then do the math to get the elapsed time in a useful format.

Finding the value of HZ (that is, jiffies per second) turns out to be ridiculously complicated! From comments in the sysinfo.c in the procps package, one can a) include the kernel header file (and recompile if a different kernel is used, b) use the posix sysconf() function, which, sadly, uses a hard-coded value compiled into the c library, or c) ask the kernel, and there's no official interface to doing that. So, the code includes a series of kludges by which it determines the correct value. Wow.
–
mattdmFeb 22 '11 at 21:54