单线程与多线程读取文件

//实验多个线程读取多个文件和单个线程读取多个文件
//当文件数量是2-3个时,单线程比多线程更快,可能是没有创建线程之类的开销
//文件数量增加到10多个以后,多个线程稍微快一点,但是并没有快多少
//按照网上的说法,读取文件的性能瓶颈是磁盘io的速度,多个线程并不能提高性能
#include <iostream>
#include <fstream>
#include <thread>
#include <string>
#include <windows.h>
using namespace std;
void ReadFileS(const char **path,int len){
	for (int i = 0; i < len;i++)
	{
		fstream fs(*(path + i), ios_base::in | ios_base::out);
		string line;
		int lineCount = 1;
		while (fs && getline(fs, line));
			//cout << "File: " << *(path + i) << "line:" << lineCount++ << ", " << line.c_str() << endl;
	}
}


void _tReadFile(const char* path){
	fstream fs(path, ios_base::in | ios_base::out);
	string line;
	int lineCount = 1;
	while (fs && getline(fs, line));
		//cout << "File: " << path << "line:" << lineCount++ << ", " << line.c_str() << endl;
}


void ReadFileM(const char **path, int len){
	for (int i = 0; i < len; i++)
	{
		std::thread t(_tReadFile,*(path+i));
		t.join();
	}
}


void main(){
	const char *path[13] = { "D:\\a.txt", "D:\\b.txt", "D:\\a.txt", "D:\\a.txt", "D:\\a.txt", "D:\\a.txt", "D:\\a.txt", "D:\\a.txt","D:\\a.txt","D:\\a.txt","D:\\a.txt","D:\\a.txt","D:\\a.txt" };
	double cost;
	double start = GetTickCount();
	ReadFileS(path, 13);
	double end = GetTickCount();
	cost = difftime(end, start);
	cout << "time diff 1------------------->" << cost << endl;


	start = GetTickCount();
	ReadFileM(path, 13);
	end = GetTickCount();
	cost = difftime(end, start);


	cout << "time diff 2------------------->" << cost << endl;


	system("pause");
}

猜你喜欢

转载自blog.csdn.net/aricover/article/details/77866635