美文网首页
线程上下文切换测试代码

线程上下文切换测试代码

作者: yanfeizhang | 来源:发表于2019-09-29 19:17 被阅读0次
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include<pthread.h>

int pipes[20][3];
char buffer[10];
int running = 1;

void inti()
{
    int i =20;
    while(i--)
    {
        if(pipe(pipes[i])<0)
            exit(1);
        pipes[i][2] = i;
    }
}

void distroy()
{
    int i =20;
    while(i--)
    {
        close(pipes[i][0]);
        close(pipes[i][1]);
    }
}

double self_test()
{
    int i =20000;
    struct timeval start, end;
    gettimeofday(&start, NULL);
    while(i--)
    {
        if(write(pipes[0][1],buffer,10)==-1)
            exit(1);
        read(pipes[0][0],buffer,10);
    }
    gettimeofday(&end, NULL);
    return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/20000;
}

void *_test(void *arg)
{
    int pos = ((int *)arg)[2];
    int in = pipes[pos][0];
    int to = pipes[(pos + 1)%20][1];
    while(running)
    {
        read(in,buffer,10);
        if(write(to,buffer,10)==-1)
            exit(1);
    }
}

double threading_test()
{
    int i = 20;
    struct timeval start, end;
    pthread_t tid;
    while(--i)
    {
        pthread_create(&tid,NULL,_test,(void *)pipes[i]);
    }
    i = 10000;
    gettimeofday(&start, NULL);
    while(i--)
    {
        if(write(pipes[1][1],buffer,10)==-1)
            exit(1);
        read(pipes[0][0],buffer,10);
    }
    gettimeofday(&end, NULL);
    running = 0;
    if(write(pipes[1][1],buffer,10)==-1)
        exit(1);
    return (double)(1000000*(end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec)/10000/20;
}


int main()
{
    inti();
    printf("%6.6f\n",self_test());
    printf("%6.6f\n",threading_test());
    distroy();
    exit(0);
}
-------------------------------------------------------------------------
Host                 OS  2p/0K 2p/16K 2p/64K 8p/16K 8p/64K 16p/16K 16p/64K  
                         ctxsw  ctxsw  ctxsw ctxsw  ctxsw   ctxsw   ctxsw  
--------- ------------- ------ ------ ------ ------ ------ ------- -------  
bjzw_46_7 Linux 2.6.32- 2.7800 2.7800 2.7000 4.3800 4.0400 4.75000 5.48000

相关文章

  • 线程上下文切换测试代码

  • 第一章 并发编程的挑战

    1.1上下文切换 多线程不一定就比单线程快,因为多线程存在上下文切换的问题、死锁的问题等问题, 测试循环累加和累减...

  • 并发编程的挑战

    目前存在的挑战 上下文切换问题线程死锁问题硬件和软件资源限制问题 上下文切换 单核处理器也支持多线程执行代码,CP...

  • Java多线程实现方式

    1.继承Thread类创建线程 线程类 测试代码 2.实现Runable接口创建线程 线程类 测试代码 3.使用线...

  • 第一章 并发编程的挑战

    并发编程相对于单线程的挑战有 上下文切换 死锁 1.常用工具 使用Lmbench可以测试上下文切换时长使用vmst...

  • 多线程-上下文切换

    多线程-上下文切换: 即使是单核处理器也支持多线程执行代码,CPU通过给每个线程分配cpu时间片来实现这个机制...

  • Python压力测试

    安装progressbar 使用多线程测试代码

  • 并发的挑战

    并发挑战 上下文切换 即使是单核处理器也支持多线程执行代码,CPU通过给每个线程分配CPU时间片来实现 这个机制。...

  • 并发编程的挑战

    上下文切换 上下文切换发生于计算机CPU从一个进程或线程切换到不同的进程或线程。 上下文切换允许一个CPU处理多个...

  • 《Java并发编程的艺术》——第1章 并发编程的挑战

    1.1 上下文切换 单核处理器也支持多线程执行代码,CPU通过给每个线程分配CPU时间片来实现这个机制。时间片是C...

网友评论

      本文标题:线程上下文切换测试代码

      本文链接:https://www.haomeiwen.com/subject/srrqpctx.html