我正在从文件中读取浮点矩阵。矩阵尺寸为 4k * 4K。使用下面的程序,它只会导致 now() 函数奇怪地重置。如果我将矩阵大小减小到 1k * 1K,它不会重置。虽然它正确读取浮点数,但最后几个值是垃圾。我不知道这些垃圾值是从哪里来的。我选择了 BUFFSIZE 6 的大小,因为它在浮点数中的位数将在 5-6 左右。不确定是否正确。
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#define ROWS 4000
#define COLS 4000
#define BUFFSIZE 6
//#define USE_FREAD
#define USE_MMAP
double now()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec / 1000000.;
}
int main()
{
double end_time;
double total_time;
int i, x, y, k;
for (k = 0; k < 1; k++)
{
double start_time = now();
FILE* in = fopen("resistence_file", "rb");
float arr[ROWS][COLS];
char temp[BUFFSIZE];
int val;
std::stringstream ss;
char* floats = (char*)mmap(
0,
ROWS * COLS * sizeof(float),
PROT_READ,
MAP_FILE | MAP_PRIVATE,
fileno(in),
0
);
fclose(in);
ss<<floats;
for (int i =0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
if ((ss.getline(temp, BUFFSIZE, ' ')) )
{
arr[i][j] = atof((temp));
}
}
}
for (int i =0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("%.1f ", arr[i][j]);
}
printf("\n");
}
munmap(floats, ROWS * COLS * sizeof(float));
end_time = now();
total_time = end_time - start_time;
printf("It took %f seconds to read %d * %d matrix \n", total_time, ROWS, COLS);
}
return 0;
}