绑定线程到指定cpu,CPU占用率像海波浪一样

Posted 帝王铠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了绑定线程到指定cpu,CPU占用率像海波浪一样相关的知识,希望对你有一定的参考价值。

#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <sched.h>
#include <thread>
#define  N  50
#define PI 3.1415926
 
int threadName(int num,int sleepnum)

    sleep(sleepnum);
printf("CPUSET%d\\n",num);
cpu_set_t  mask;
CPU_ZERO(&mask);
CPU_SET(num, &mask);
sched_setaffinity(0, sizeof(mask), &mask);

 
    int T = 10000;   // 10s
    int i;
    double busy[N], idle[N];
    double interval = (double)T / N ; //ms 
 
//算出每个interval的空闲时间和繁忙时间
    for(i = 0; i < N; i ++)
    
        busy[i] = ((sin(2 * PI * i / N)/2 + 0.5) * 50 + 25 )/100 * interval;
        idle[i] =  interval - busy[i];
        //printf("%d %.2lf %.2lf\\n", i, busy[i], idle[i]);
    
 
    int j = 0;
    struct timeval  start_timeval;
    struct timeval  cur_timeval; 
     
    while (true)
    
        gettimeofday(&start_timeval, NULL); 
        double last_ms = (double)start_timeval.tv_sec * 1000 + start_timeval.tv_usec/1000 ;
        while (true)
        
            gettimeofday(&cur_timeval, NULL);
            double cur_ms = (double)cur_timeval.tv_sec * 1000 + cur_timeval.tv_usec/1000 ;
            if (cur_ms - last_ms >= busy[j])
                break;
        
 
        usleep(idle[j] * 1000);
        j = (j + 1) % N;
    
 
    exit(1);



int main()

    std::thread t1(threadName,0,0);
    std::thread t2(threadName,1,1);
    std::thread t3(threadName,2,2);
    std::thread t4(threadName,3,3);
    std::thread t5(threadName,4,4);
    std::thread t6(threadName,5,5);
    std::thread t7(threadName,6,6);
    std::thread t8(threadName,7,7);
    std::thread t9(threadName,8,8);
    std::thread t10(threadName,9,9);
    std::thread t11(threadName,10,10);
    std::thread t12(threadName,11,11);


    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t6.join();
    t7.join();
    t8.join();
    t9.join();
    t10.join();
    t11.join();
    t12.join();



CPU是i7-8700,12逻辑核心,
操作系统:中兴国产系统

以上是关于绑定线程到指定cpu,CPU占用率像海波浪一样的主要内容,如果未能解决你的问题,请参考以下文章

cpu的线程越多占用率越低吗?还是取决于核心数?

如何查看 android 线程 cpu占用率

linux查看线程占用cpu

java 多线程 cpu 占用率高的问题

Linux下CPU占用率高分析方法

Linux下分析某个进程CPU占用率高的原因