thread_cputime Subroutine
Purpose
Retrieves CPU usage for a specified thread
Library
Standard C library (libc.a)
Syntax
#include <sys/thread.h>
int thread_cputime (tid, ctime)
tid_t tid;
thread_cputime_t * ctime ;
typedef struct {
uint64_t utime; /* User time in nanosenconds */
uint64_t stime; /* System time in nanoseconds */
} thread_cputime_t;
Description
The thread_cputime subroutine allows a thread to query the CPU usage of the specified thread (tid) in the same process or in another process. If a value of -1 is passed in the tid parameter field, then the CPU usage of the calling thread is retrieved.
CPU usage is not the same as the total life of the thread in real time, rather it is the actual amount of CPU time consumed by the thread since it was created. The CPU usage retrieved by this subroutine contains the CPU time consumed by the requested thread tid in user space (utime) and system space (stime).
The thread to be queried is identified using the kernel thread ID which has global scope. This can be obtained by the application using the thread_self system call. Only 1:1 thread mode is supported. The result for M:N thread mode is undefined.
The CPU usage of a thread that is not the calling thread will be current as of the last time the thread was dispatched. This value will be off by a small amount if the target thread is currently running.
Parameters
Item | Description |
---|---|
tid | Identifier of thread for which CPU usage is to be retrieved. A value of -1 will cause the CPU usage of the calling thread to be retrieved. |
ctime | CPU usage returned to the caller. The CPU usage is returned in terms of nanoseconds of system and user time. |
Return Values
- 0
- thread_cputime was successful
- -1
- thread_cputime was unsuccessful. Global variable errno is set to indicate the error.
Error Codes
The thread_cputime subroutine is unsuccessful if one or more of the following is true:
Item | Description |
---|---|
ESRCH | The target thread could not be found. |
EINVAL | One or more of the arguments had an invalid value. |
EFAULT | A copy operation to ctime failed. |
Example
#include <stdio.h>
#include <sys/thread.h>
cputime.c:
int main( int argc, char *argv[])
{
thread_cputime_t ut;
tid_t tid;
tid = atoi(argv[1]);
printf("tid = %d\n",tid);
if (thread_cputime(tid, &ut) == -1)
{
perror("Error from thread_cputime");
exit(0);
}
else
{
printf("U: %ld nsecs\n", ut.utime);
printf("S: %ld nsecs\n", ut.stime);
}
}
Output:
# tcpdump -i en0 > /dev/null &
# echo "th * | grep tcpdump" | kdb | grep tcpdump
(0)> th * | grep tcpdump
pvthread+00A700 167 tcpdump SLEEP 0A7011 044 0 0 nethsque+000290
# echo "ibase=16;obase=A;0A7011" | bc
684049
# ./cputime 684049
tid = 684049
U: 31954040 nsecs
S: 31833069 nsecs