Linux 多线程速度测试

测试程序:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
 
#define    NUM_THREADS  8
 
static sem_t m_sem;
pthread_mutex_t mutex;
 
void *PrintHello(void *args)
{
    int thread_arg;
    unsigned int i,j;
    //static n = 0;
    struct timeval start, end;
    float time_use=0;
 
    thread_arg = (int)(*((int*)args));
    i = 0;j = 0;
    //printf("n=%d\n",n);
    //n++;
 
    gettimeofday(&start, NULL);
 
    while(1)
    {
        sem_post(&m_sem);
        sem_wait(&m_sem);
        if(j > 10000000) break;
        pthread_mutex_lock(&mutex);
        j++;
        pthread_mutex_unlock(&mutex);
        //printf("Hello from thread %d\n", thread_arg);
        i++;
        if( 0 == i%100)        usleep(1);
        //usleep(1);
    }
    gettimeofday(&end, NULL);
    time_use=(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec);//微秒
    printf("thread %d exit, duration is %.3fms\n",thread_arg,time_use/1000.0);
 
    return NULL;
}
 
int main(void)
{
    int rc,t;
    int *p_thread_id;
    pthread_t thread[NUM_THREADS];
    int res;
    struct timeval start, end;
    float time_use=0;
 
    gettimeofday(&start, NULL);
 
    res = sem_init(&m_sem, 0, 0);
    if (res != 0)
    {
        printf("Semaphore initialization failed\n");
    }
 
    pthread_mutex_init (&mutex, NULL);
 
    p_thread_id = (int *)malloc(sizeof(int));
 
    for( t = 0; t < NUM_THREADS; t++)
    {
        *p_thread_id = t;
        //printf("Creating thread %d\n", *p_thread_id);
        rc = pthread_create(&thread[t], NULL, PrintHello, p_thread_id);
        if (rc)
        {
            printf("ERROR; return code is %d\n", rc);
            return EXIT_FAILURE;
        }
        usleep(1);//必须sleep
    }
 
    //printf("pthread_create end\n");
    for( t = 0; t < NUM_THREADS; t++)
        pthread_join(thread[t], NULL);
 
    gettimeofday(&end, NULL);
    time_use=(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec);//微秒
    printf("all threads exit,  duration is %.3fms\n",time_use/1000);
 
    printf("exit success\n");
    return EXIT_SUCCESS;
}
测试结果:

不用互斥锁mutex
1.用信号量m_sem和不用信号量(也不用睡眠)比较。都会使cpu占用率达到100%,使用信号量会使速度下降很多。
2.使用usleep,会使cpu占用率下降很多,速度比用信号量明显要快。
3.既不用usleep,也不用信号量,速度最快,但会使cpu占用率达到100%。

用互斥锁mutex
4.循环100次,用一次usleep(1),占用cpu最少,运行最快。
5.除了4的情况,测试的其他情况cpu占用率都比较高,但都没到100%。
6.所有测试,运行速率差别不大,用时最低是8587.839ms,最高是11085.287ms。

7.用互斥锁,比不用互斥锁速度慢。
8.只用互斥锁和只用信号量的速度差不多。

以上结果是在我机器上的测试结果,机器型号不同,结果可能不同。

尽可能不使用互斥锁,多通道多队列的方式。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乾 乾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值