我有一个基于命令行选项执行以下操作的测试程序:
1)fork多个进程,每个进程完全顺序读取同一个文本文件
2)创建多个线程,每个线程完全顺序读取同一个文本文件
我注意到多线程方法比多进程方法多花费大约 35% 的时间。
为什么多进程 IO 比多线程 IO 快?
机器配置:8GB RAM,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
真实 0m26.170s 用户 1m40.149s 系统 0m3.360s
多线程耗时:
时间 ./io_test t 20
真实 0m35.561s 用户 2m14.245s 系统 0m4.577s