您的位置:首页 > 其它

测试创建和销毁进程开销于创建和销毁线程开销对比

2010-04-22 15:51 447 查看
//对比进程创建和线程创建的时间开销
#include    <stdio.h>
#include    <stdlib.h>
#include    <unistd.h>
#include    <sys/time.h>
#include    <pthread.h>
void* thr_fun(void* arg)
{
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
struct timeval tv1;
struct timeval tv2;
unsigned long long t1, t2;
int i;
pid_t pid;
pthread_t tid;
if( gettimeofday(&tv1, NULL)!=0 )
{
perror("gettimeofday");
exit(1);
}
for( i=0 ; i<10000 ; i++ )
{
pid=fork();
if( pid<0 )
{
perror("fork");
exit(1);
}
else if( 0==pid )
{
exit(0);
}
else
{
wait(NULL);
}
}
if( gettimeofday(&tv2, NULL)!=0 )
{
perror("gettimeofday");
exit(1);
}
t1=(tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec);
printf("生成和销毁10000个进程共耗时%Lu微妙/n", t1);

if( gettimeofday(&tv1, NULL)!=0 )
{
perror("gettimeofday");
exit(1);
}
for( i=0 ; i<10000 ; i++ )
{
if( pthread_create(&tid, NULL, thr_fun, NULL)!=0 )
{
perror("pthread_create");
exit(1);
}
pthread_join(tid, NULL);
}
if( gettimeofday(&tv2, NULL)!=0 )
{
perror("gettimeofday");
exit(1);
}
t2=(tv2.tv_sec-tv1.tv_sec)*1000000+(tv2.tv_usec-tv1.tv_usec);
printf("生成和销毁10000个线程共耗时%Lu微妙/n", t2);
printf("进程是线程开销的%f倍/n", (double)t1/(double)t2);

exit(0);

}


进程的开销大概是线程的10倍,但不一定准。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: