多核多线程——pthread_setaffinity_np,cpulimit分析CPU资源对应用程序的影响

我们在设计多核多线程程序方案的时候,有时候需要比较不同程序设计方案的性能的区别。比如:同一程序在不同处理器之间切换,充分利用闲置的CPU资源或是了解不同线程绑定在不同CPU资源上的性能等等问题。这里我们可以使用pthread_setaffinity,pthread_getaffinity以及cpulimit配合使用来达到我们的目的。

在linux系统下我们不希望某个线程完全占据了某一CPU的全部性能,可以使用cpulimit在限制某个线程在使用该CPU的运行性能。

在ubuntu中我们可以使用以下命令来安装cpulimit。

$sudo apt-get update

$sudo apt-get install cpulimit

具体的使用以下二种不同的方法:(限制text线程在CPU上的运行性能不超过50%,假设线程text的PID号为1234,PID可以通过top命令查看)

A.cpulimit -e  text -l 50

B.cpulimit -p 1234 -l 50 (PID号可以通过TOP查看)


关于pthread_setaffinity和pthread_getaffinity的介绍以及具体的使用方法:

pthread_setaffinity和pthread_getaffinity是用来设置和获取某一线程和CPU的亲和性的。简单来讲就是:某一线程跑在了哪个CPU上以及某个CPU上都跑了哪些线程;表示线程和CPU之间关系的函数。

在使用它们之前,需要做一些准备工作:

#define  _GNU_SOURCE

#include<pthread.h>

int pthread_setaffinity_np(pthread_t thread,size_t cpusetsize,const cpu_set_t *cpuset);

int pthread_getaffinity_np(pthread_t thread,size_t cpusetsize, cpu_set_t *cpuset);

(这里出现了一个陌生的结构体:cpu_set_t,可以理解为一个CPU的集合,通过约定好的宏进行清除,设置以及判断)

同时在使用时我们会有一些初始化的操作:

void CPU_ZERO(cpu_set_t  *set);(初始化操作)

void CPU_SET(int cpu,cpu_set_t *set)(将某个cpu加进cpu集里)

void CPU_CLR(int cpu,cpu_set_t *set)(将某个cpu清除出cpu集里)

void CPU_ISSET(int cpu,const cpu_set_t *set)(判断某个cpu是不是在cpu集里)

应用程式代码:

#define _GNU_SOURCE
#include <stdio.h>
#include <math.h>
#include <pthread.h>
cpu_set_t cpuset,cpuget;
double waste_time(long n)
{
double res = 0;
long i = 0;
while (i <n * 200000000) {
i++;
res += sqrt(i);
}
return res;
}
void *thread_func(void *param)
{   
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset); /* cpu 0 is in cpuset now */
/* bind process to processor 0 */
if (pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) !=0) {
perror("pthread_setaffinity_np");
}  
printf("Core 0 is running!\n");
/* waste some time so the work is visible with "top" */
 printf("result: %f\n", waste_time(5));
pthread_exit(NULL);
}
int main(int argc, char *argv[])

pthread_t my_thread;
time_t startwtime, endwtime;
startwtime = time (NULL); 
if (pthread_create(&my_thread, NULL, thread_func,NULL) != 0) {
perror("pthread_create");
}
pthread_join(my_thread,NULL);
endwtime = time (NULL);
printf ("wall clock time = %d\n", (endwtime - startwtime));
return 0;
}
这段
程序是用来测试线程thread_func跑在CPU0上的所用时间。对应的可以更改程序实现你所需要的测试功能。

为了方便观察CPU使用率,我们可以ubuntu的Dash主页键入system monitor来直观的查看CPU的使用情况,从而找到最适合的多核多线程设计方案。

	
 

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值