名称

pthread_getcpuclockid-检索线程的CPU时间时钟的ID

说明

pthread_getcpuclockid()函数获取其ID在线程中给出的线程的CPU时间时钟的ID,并将其返回到Clockid指向的位置。

版本

从2.2版开始,此功能在glibc中可用。

示例

下面的程序创建一个线程,然后使用clock_gettime(2)检索总进程CPU时间以及两个线程消耗的每线程CPU时间。以下shell会话显示了一个示例运行:

$ ./a.out
Main thread sleeping
Subthread starting infinite loop
Main thread consuming some CPU time...
Process total CPU time:    1.368
Main thread CPU time:      0.376
Subthread CPU time:        0.992

Program source

/* Link with "-lrt" */

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>

#define handle_error(msg) \
        do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

static void *
thread_start(void *arg)
{
    printf("Subthread starting infinite loop\n");
    for (;;)
        continue;
}

static void
pclock(char *msg, clockid_t cid)
{
    struct timespec ts;

    printf("%s", msg);
    if (clock_gettime(cid, &ts) == -1)
        handle_error("clock_gettime");
    printf("%4ld.%03ld\n", ts.tv_sec, ts.tv_nsec / 1000000);
}

int
main(int argc, char *argv[])
{
    pthread_t thread;
    clockid_t cid;
    int j, s;

    s = pthread_create(&thread, NULL, thread_start, NULL);
    if (s != 0)
        handle_error_en(s, "pthread_create");

    printf("Main thread sleeping\n");
    sleep(1);

    printf("Main thread consuming some CPU time...\n");
    for (j = 0; j < 2000000; j++)
        getppid();

    pclock("Process total CPU time: ", CLOCK_PROCESS_CPUTIME_ID);

    s = pthread_getcpuclockid(pthread_self(), &cid);
    if (s != 0)
        handle_error_en(s, "pthread_getcpuclockid");
    pclock("Main thread CPU time:   ", cid);

    /* The preceding 4 lines of code could have been replaced by:
       pclock("Main thread CPU time:   ", CLOCK_THREAD_CPUTIME_ID); */

    s = pthread_getcpuclockid(thread, &cid);
    if (s != 0)
        handle_error_en(s, "pthread_getcpuclockid");
    pclock("Subthread CPU time: 1    ", cid);

    exit(EXIT_SUCCESS);         /* Terminates both threads */
}

出版信息

这个页面是Linux手册页项目5.08版的一部分。有关项目的说明、有关报告错误的信息以及此页面的最新版本,请访问https://www.kernel.org/doc/man-pages/

返回值

成功时,此函数返回0;否则,返回0。如果出错,则返回非零错误号。

语法

#include <pthread.h>
#include <time.h>

int pthread_getcpuclockid(pthread_t thread, clockid_t *clockid);

Compile and link with -pthread.
PTHREAD_GETCPUCLOCKID - Linux手册页

Linux程序员手册 第3部分
更新日期: 2020-06-09

备注

当线程引用调用线程时,此函数返回一个标识符,该标识符引用给定时钟ID CLOCK_THREAD_CPUTIME_ID时由clock_gettime(2)和clock_settime(2)操纵的同一时钟。

错误说明

ENOENT
系统不支持按线程的CPU时间时钟。
ESRCH
找不到具有ID线程的线程。

属性

有关本节中使用的术语的说明,请参见attribute(7)。

InterfaceAttributeValue
pthread_getcpuclockid()Thread safetyMT-Safe

遵循规范

POSIX.1-2001,POSIX.1-2008。

日期:2019-08-20 18:01:03 来源:oir作者:oir