gpt4 book ai didi

C++ Windows API 比 ifstream 慢?还有别的办法吗?

转载 作者:行者123 更新时间:2023-11-28 07:09:41 25 4
gpt4 key购买 nike

我有一个 5MB 制表符分隔的文件需要读入。我正在使用 ifstream 并且还尝试将 CreateFileReadFile 一起使用或 CreateFileMapping,但这两种 Windows 实现比使用 ifstream 花费的时间稍长。

我错过了什么重要的东西吗?从 SO 和 Google 我的印象是使用 Windows api 会加快速度。

抱歉,代码量太大,我想提供完整的功能,因为我不知道问题出在哪里。

如有任何建议,我们将不胜感激!

ifstreams:

void ifstream_read(string file_name)
{
string line, word;
ifstream inf;
vector<string> current_record;
inf.open(file_name.c_str()); //char*
while (! inf.eof() )
{
current_record.clear();
getline(inf, line);
istringstream iss(line);
while (iss >> word)
{
current_record.push_back(word);
}

//save current_record in my dataset
}

}

带有 ReadFile 的 Windows:

#define BUFFER_SIZE 8192

void windows_read(wstring file)
{
HANDLE file_handle = INVALID_HANDLE_VALUE;
LPCWSTR file_name = (LPCWSTR)file.c_str();
DWORD bytes_read = 0;
char read_buffer[BUFFER_SIZE] = {0};
bool complete = false;
stringstream ss;

file_handle = CreateFile(file_name,
GENERIC_READ, // open for reading
NULL, // do not share
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_FLAG_SEQUENTIAL_SCAN, // normal file
NULL);
while(!complete)
{
ReadFile(file_handle, read_buffer, BUFFER_SIZE-1, &bytes_read, NULL);

if(bytes_read < BUFFER_SIZE-1)
{
complete = true;
read_buffer[bytes_read] = '\0';
}
ss << read_buffer;
}
CloseHandle(file_handle);

vector<string> current_record;
string line, word;
while(getline(ss, line, '\n'))
{
current_record.clear();
istringstream iss(line);
while (iss >> word)
{
current_record.push_back(word);
}

//save current_record in my dataset
}
}

Windows 文件映射:

void windows_map(wstring file)
{
HANDLE file_handle = INVALID_HANDLE_VALUE;
LPCWSTR file_name = (LPCWSTR)file.c_str();
stringstream ss;

file_handle = CreateFile(file_name,
GENERIC_READ, // open for reading
NULL, // do not share
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_FLAG_SEQUENTIAL_SCAN, // normal file
NULL);

HANDLE file_map = CreateFileMapping(file_handle, NULL, PAGE_READONLY, 0, 0, NULL);
LPVOID file_view = MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 0);

ss << (char*)file_view;

UnmapViewOfFile(file_view);
CloseHandle(file_map);
CloseHandle(file_handle);

vector<string> current_record;
string line, word;
while(getline(ss, line, '\n'))
{
current_record.clear();
istringstream iss(line);
while (iss >> word)
{
current_record.push_back(word);
}

// save current_record to dataset
}
}

最佳答案

因此,您正在比较一辆载有 2 名乘客的车辆和另一辆满载行李的车辆的速度。你不能称之为比较。在相同的负载、相同的道路、相同的道路和天气条件下运行两辆车。

同样,不要使用逐字节复制到 C 字符串,然后将其放入 vector 中。在我看来,直接把内容读入内存,看不同的读法有多快。我会说,甚至不要使用一些大内存(巨大的 newed 数组或 vector )。只需使用一个缓冲区(或 string 对象),并继续覆盖它。

在完全相同的文件(在相同的驱动器上)上进行发布构建以进行性能测试。

关于C++ Windows API 比 ifstream 慢?还有别的办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21208354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com