我有一个测试程序,它根据命令行选项执行以下操作:
1)分叉多个进程,每个进程按顺序读取相同的文本文件
2)创建多个线程,每个线程依次读取相同的文本文件。
我已经注意到,多线程方法比多进程方法多花费35 %的时间。
为什么多进程IO比多线程IO更快?
机器配置: 8GB内存,4核,
下面是代码和测试结果:
using namespace std;
#include<fstream>
#include<iostream>
#include<pthread.h>
#include<errno.h>
#include<sys/wait.h>
#include <string>
void* run_thread(void * tmp)
{
int counter=0;
string s;
string input_file("perf_input");
ifstream in(input_file.c_str(), ios_base::in);
while(getline(in, s))
{
counter++;
}
cout<<"counter "<<counter<<endl;
}
int main(int argc, char *argv[])
{
if(argc != 3)
{
cout<<"Invalid number of arguments "<<endl;
return -1;
}
if(argv[1][0] == 'p')
{
cout<<"fork process"<<endl;
int n = atoi(argv[2]);
cout<<" n " <<n<<endl;
for(int i=0;i<n;i++)
{
int cpid = fork();
if(cpid< 0)
{
cout<<"Fork failed "<<endl;
exit(0);
}
else if(cpid == 0)
{
//child
cout<<"Child created "<<endl;
run_thread(NULL);
cout<<"Child exiting "<<endl;
exit(0);
}
}
while (waitpid(-1, NULL, 0))
{
if (errno == ECHILD)
{
break;
}
}
}
else
{
cout<<"create thread"<<endl;
int n = atoi(argv[2]);
cout<<" n " <<n<<endl;
pthread_t *tids = new pthread_t[n];
for(int i=0;i <n; i++)
{
pthread_create(tids + i, NULL, run_thread, NULL);
}
for(int i=0;i <n; i++)
{
pthread_join(*(tids + i), NULL);
}
}
}多进程所需时间:
时间。/io_test p 20。
实际用户1m40.149ssys 0m3.360
多线程所需时间:
时间。/io_t 20
实0m35.561 s用户2m14.245 s系统0m4.577 s
发布于 2013-12-14 15:49:32
我怀疑您是在一些带有默认内核IO设置的现代桌面Linux发行版上测试的--这就是我怀疑找到答案的地方。
https://stackoverflow.com/questions/20585132
复制相似问题