멀티 스레드보다 빠른 명령 줄 옵션에 따라 다음Mutiproccess IO 내가 수행하는 테스트 프로그램을 IO
1) 포크 여러 프로세스와 각 프로세스가 완전히 같은 텍스트 파일을 순차적으로 읽고
2) 여러 스레드를 만들고 각 스레드가 동일한 텍스트 파일을 순차적으로 읽습니다.
다중 스레드 접근 방식은 다중 프로세스 접근 방식보다 약 35 % 더 많은 시간이 걸렸습니다.
왜 다중 프로세서 IO가 다중 스레드 IO보다 빠릅니까?
기계 설정 : 8기가바이트 RAM, 4 코어, 여기
인 코드와 테스트 결과 :시간 ./io_test : 다중 프로세스에 대해 수행
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);
}
}
}
시간 p 20
진짜 0m26.170s 사용자 1m40.149s 개에 sys 0m3.360s
시간은 멀티 스레드를 위해 촬영 :
시간 ./io_test t 20
실제 0m35.561s 사용자 2m14.245s 에 sys 0m4.577s
다중 스레드를 사용할 때'ifstream'이 잠금을 사용해야합니다. 그것이 맞다면 파일의 길이가 길어질수록 차이가 줄어들 것입니다. – zch