nanosleep睡眠时间太长60微秒

时间:2016-05-08 23:36:01

标签: linux cpu sleep

我用g ++编译了以下测试,纳米睡眠时间太长,需要  完成60微秒,我预计它的成本只有不到1微秒:

int main()
{
    gettimeofday(&startx, NULL);
    struct timespec req={0};
    req.tv_sec=0;
    req.tv_nsec=100 ;
    nanosleep(&req,NULL) ;
    gettimeofday(&endx, NULL);
    printf("(%d)(%d)\n",startx.tv_sec,startx.tv_usec);
    printf("(%d)(%d)\n",endx.tv_sec,endx.tv_usec);
    return 0 ;
}

我的环境:uname -r showes:

3.10.0-123.el7.x86_64

cat / boot / config - uname -r | grep HZ

CONFIG_NO_HZ_COMMON=y
# CONFIG_HZ_PERIODIC is not set
# CONFIG_NO_HZ_IDLE is not set
CONFIG_NO_HZ_FULL=y
# CONFIG_NO_HZ_FULL_ALL is not set
CONFIG_NO_HZ=y
# CONFIG_RCU_FAST_NO_HZ is not set
# CONFIG_HZ_100 is not set
# CONFIG_HZ_250 is not set
# CONFIG_HZ_300 is not set
CONFIG_HZ_1000=y
CONFIG_HZ=1000
CONFIG_MACHZ_WDT=m

我应该在HZ配置中做些什么,这样nanosleep会完全符合我的期望吗?!

我的cpu信息:

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                24
On-line CPU(s) list:   0-23
Thread(s) per core:    2
Core(s) per socket:    6
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 63
Model name:            Intel(R) Xeon(R) CPU E5-2643 v3 @ 3.40GHz
Stepping:              2
CPU MHz:               3600.015
BogoMIPS:              6804.22
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              20480K
NUMA node0 CPU(s):     0,2,4,6,8,10,12,14,16,18,20,22
NUMA node1 CPU(s):     1,3,5,7,9,11,13,15,17,19,21,23

编辑:

#ifdef SYS_gettid
    pid_t tid = syscall(SYS_gettid);
    printf("thread1...tid=(%d)\n",tid);
#else
    #error "SYS_gettid unavailable on this system"
#endif

这将得到我喜欢高优先级的线程的tid,然后做 chrt -v -r -p 99为达到这个目标,感谢Johan Boule 亲切的帮助,非常感谢!!!

Edit2:

#ifdef SYS_gettid
    const char *sched_policy[] = {
    "SCHED_OTHER",
    "SCHED_FIFO",
    "SCHED_RR",
    "SCHED_BATCH"
    };
    struct sched_param sp = {
        .sched_priority = 99
    };
    pid_t tid = syscall(SYS_gettid);
    printf("thread1...tid=(%d)\n",tid);
    sched_setscheduler(tid, SCHED_RR, &sp);
    printf("Scheduler Policy is %s.\n", sched_policy[sched_getscheduler(0)]);
#else
    #error "SYS_gettid unavailable on this system"
#endif

如果没有chrt的帮助,这将完全符合我的要求

1 个答案:

答案 0 :(得分:2)

(这不是答案)

值得一提的是,使用更现代的功能会产生相同的结果:

foo

输出:

#include <stddef.h>
#include <time.h>
#include <stdio.h>

int main()
{
    struct timespec startx, endx;
    clock_gettime(CLOCK_MONOTONIC, &startx);
    struct timespec req={0};
    req.tv_sec=0;
    req.tv_nsec=100 ;
    clock_nanosleep(CLOCK_MONOTONIC, 0, &req, NULL);
    clock_gettime(CLOCK_MONOTONIC, &endx);
    printf("(%d)(%d)\n",startx.tv_sec,startx.tv_nsec);
    printf("(%d)(%d)\n",endx.tv_sec,endx.tv_nsec);
    return 0 ;
}