Chinaunix首页 | 论坛 | 博客
  • 博客访问: 65746
  • 博文数量: 42
  • 博客积分: 1730
  • 博客等级: 上尉
  • 技术积分: 430
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-02 13:06
文章分类

全部博文(42)

文章存档

2011年(1)

2009年(41)

我的朋友

分类: LINUX

2009-08-24 20:37:26

多线程和多进程运行时间比较:

    我的思路是:

一个程序创建5个子进程,并执行一段代码,分别统计这5个进程运行的时间,取最大的为整个程序运行时间(粗略估计)

一个程序创建5个子线程,并执行一段代码,分别统计这5个线程运行的时间,取最大的为整个程序运行时间(粗略估计)

我不知道我这样的做法是否合理,不妥之处还请大家指教。或者大家还有什么其他的计算多进程或多线程运行时间的方法。


 

多进程:
#include <stdio.h>
#include <time.h>

void function();

int main()
{
    int j;

  for(j = 0 ; j < 5 ; j++)
  {
          int pid = fork();
          if(pid == 0)
          {    
                     clock_t start,end;
                    start = clock();             
                    printf("here!\n");
                  function();
                  end = clock();
                  printf("%d\n",end-start);
                  exit(0);
          }
  }
}

void function()
{
    int i;
    for(i = 0 ; i < 1000000000 ; i++)
    {
        ;
    }    
}

最后运行时间:
3090000
3040000
3020000
3010000
3000000
取最大: 3090000


多线程:
#include <stdio.h>
#include <time.h>
#include <pthread.h>

void *function();

int main()
{
    int j;
    pthread_t tid;
  for(j = 0 ; j < 5 ; j++)
  {
            pthread_create(&tid , NULL , (void *)function , NULL);
  }
  while(1);
}

void *function()
{
    int i;
    clock_t start,end;
    start = clock();
    printf("here!\n");
    for(i = 0 ; i < 10000000 ; i++)
    {
        ;
    }    
    end = clock();
    printf("%d\n",end-start);    
}

运行结果:
150000
240000
250000
250000
260000
取最大:260000

结论:多线程比多线程相对系统开销小,运行要快点

阅读(914) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~