快速读取文件

时间:2015-06-19 19:16:27

标签: c input graph text-files

我有一个txt文件,其中包含2个图形和以下格式的顶点数:

6
0 1 0 1 0 0
1 0 1 0 0 1
0 1 0 1 0 0
1 0 1 0 1 0
0 0 0 1 0 1
0 1 0 0 1 0
0 1 0 0 1 0
1 0 1 0 0 0
0 1 0 1 0 1
0 0 1 0 1 0
1 0 0 1 0 1
0 0 1 0 1 0

矩阵表示顶点邻接。如果两个顶点相邻,则它们的对为1。 尽管图形未在视觉上分离,但第二个图形在第一个图形的第6行之后开始。 每个图可以有很多顶点,比如5000,它们都是相同的大小(图形)。 我写了一个算法,检查两个图是否同构,我注意到读取图形需要8秒,实际算法需要2.5(对于5000个顶点)。 由于我的目标是优化程序的整体速度,我想知道我是否可以改进(就速度而言)我目前的文件阅读代码:

FILE* file = fopen ("input.txt", "r");
fscanf (file, "%d", &i);
int n = i;
while (!feof (file))
{  
    fscanf (file, "%d", &i); 
    if (j < (n*n)) {  // first graph
        if (i==1) {
            adj_1[j/n][v_rank_1[j/n]] = j - (j/n)*n; // add the vertice to the adjacents of the current vertice
            v_rank_1[j/n] += 1;
        }
    }
    else if (j>=(n*n)) {   // second graph
        if (i==1) {
            adj_2[(j-(n*n))/n][v_rank_2[(j-(n*n))/n]] = (j-(n*n)) - ((j-(n*n))/n)*n; // add the vertice to the adjacents of the current vertice
            v_rank_2[(j-(n*n))/n] += 1;
        }
    }
    j++;
}
fclose (file);

adj_*表保存顶点的相邻顶点的索引

v_rank_*表保存与顶点相邻的顶点数

重要的是我从图表中获取此信息并仅获取此信息。

3 个答案:

答案 0 :(得分:3)

第一个优化是一次性读取内存中的整个文件。在循环中访问内存比调用fread更快。

第二个优化是少做一次运动操作,即使它意味着更多的代码。

第三种优化是将文件中的数据视为字符,以避免整数转换。

结果可能是:

// bulk read file into memory
fseek(file, 0, SEEK_END);
long fsize = ftell(file);
fseek(file, 0, SEEK_SET);
char *memFile = malloc(fsize + 1);
if (memFile == NULL) return; // not enough memory !! Handle it as you wish
fscanf(file, "%d", &n);
fread(memFile, fsize, 1, file);
fclose(file);
memfile[fsize] = 0;

// more code but less arythmetic operations
int lig, col;
char *mem = memFile, c;
for (int lig = 0; lig < n; lig++) { // first graph
    for (int col = 0; col < n; col++) {
        for (;;)
        {
            c = *mem;
            if (c == 0) break;
            mem++;
            if (c == '1') {
                adj_1[lig][v_rank_1[lig]++] = col; // add the vertice to the adjacents of the current vertice
                k++; // ??
                break;
            }
            if (c == '0') break;
        }

    }
}
for (int lig = 0; lig < n; lig++) { // second graph
    for (int col = 0; col < n; col++) {
            c = *mem;
            if (c == 0) break;
            mem++;
            if (c == '1') {
                adj_2[(lig][v_rank_2[lig]++] = col; // add the vertice to the adjacents of the current vertice
                l++;  // ??
                break;
            }
            if (c == '0') break;
        }
    }
}
free(memFile);

备注:您对变量kl一无所知。

答案 1 :(得分:2)

您可以通过较少访问文件系统来加快速度。您正在从文件中一次读取一个整数,从而每次通过循环访问文件。

相反,请尝试一次读取整个文件或大块文件。 (这称为块读取)。您可以将其缓冲到数组中。在循环内部,从内存缓冲区而不是文件中读取。如果您没有读入整个文件,请在循环内根据需要刷新内存缓冲区。

答案 2 :(得分:0)

使用fgets()一次读取一行到行缓冲区。将行缓冲区解析为整数值。

此函数减少了从文件中读取的次数,因为在幕后,fgets()从文件中读取大量数据并一次返回一行。当内部缓冲区中没有剩余行时,它只会尝试读取另一个块。

相关问题