gpt4 book ai didi

c++ 无法改进文件读取?

转载 作者:行者123 更新时间:2023-11-27 23:54:30 25 4
gpt4 key购买 nike

我有一个用 C++ 编写的代码,用于读取一个非常大的数据文件(10-20 步)。我读了每一行,它很长。有什么办法可以提高效率吗?

我知道有一些关于此的帖子,但我的问题并不完全相同...

该文件包含 N 个原子的坐标及其在给定时间的速度。

我的代码:

void Funct(std::string path, float TimeToRead, int nbLines, float x[], float y[], float z[], float vx[], float vy[], float vz[], std::string names[], int index[])
{
ifstream file(path.c_str());
if (file)
{
/* x,y,z are arrays like float x[nbAtoms] */

while (time != TimetoRead) {
/*I Put the cursor at the given time to read before*/
/*And then read atoms coordinates*/
}

for (int i = 0; i < nbAtoms; i++) {
file >> x[i]; file >> y[i]; /* etc, load all*/
}
}
}

int main()
{
/*Declarations : hidden*/

for (int TimeToRead = 0; TimeToRead<finalTime; TimeToRead++) {
Funct(...);
/*Do some Calculus on the atoms coordinates at one given time */
}
}

目前我有大约 200 万行,每行有 8 或 9 列数字。该文件是一个给定时间的一系列原子坐标。

我必须对每个时间步进行计算,所以我现在为每个时间步调用此函数(大约 4000 个时间步并且有大量原子)。最后是非常昂贵的时间。

我在某处读到我可以将一行保存在内存中而不是每次都读取文件但是当文件是 20Go 时我不能真正将它全部保存在 RAM 中!

我可以做些什么来提高阅读能力?

非常感谢

Edit1:我在 Linux 上

编辑2:要读取的文件包含一个行标题,如:

time= 1
coordinates atom 1
coordinate atom 2
...
...
...
time=2
coordinates atom 1
coordinate atom 2
...
...
...
etc

while 循环只是从头开始读取每一行,直到他找到 t= TimeToRead

最佳答案

我认为有可能优化(删除)跳行代码(while (time != TimetoRead))

你在每次迭代中打开你的文件,然后你总是跳过大量的行。如果您的文件包含 finalTime 记录,则在第一次迭代时跳过 0 条记录,在第二次迭代时跳过 1 条记录,依此类推。总共跳过 0+1+2+...(finalTime-1) 条记录,即 (finalTime-1) *(finalTime)/2 :-) 将其乘以每条记录的行数,您会发现大部分时间可能会浪费在什么地方。

解决方案可能是:将文件打开操作从您的读取方法提取到周围的代码中。这样你读取一条记录,然后进行微积分,然后当你读取下一条记录时,你不必再次打开文件并跳过所有这些行,因为流将自动在正确的位置继续。

在“伪代码”中应该是这样的:

void Funct(ifstream file, ...)
{
if (file)
{
/* x,y,z are arrays like float x[nbAtoms] */

for (int i = 0; i < nbAtoms; i++) {
file >> x[i]; file >> y[i]; /* etc, load all*/
}
}
}

int main()
{
ifstream file(path.c_str());

for (int TimeToRead = 0; TimeToRead<finalTime; TimeToRead++) {
Funct(file, ...);
/*Do some Calculus on the atoms coordinates at one given time */
}
}

关于c++ 无法改进文件读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640646/

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