单线程与多线程读取文件

//实验多个线程读取多个文件和单个线程读取多个文件
//当文件数量是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");
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值