简体   繁体   English

在C中加快许多UNIX读/写调用的速度

[英]Speed up many UNIX read/write calls in C

I'm writing a program (fair warning, it's a homework problem) that will be sorting 50 million floats it receives as an input file and outputting them to another file. 我正在编写一个程序(警告,这是一个家庭作业问题),它将对作为输入文件接收的5000万浮点数进行排序,并将其输出到另一个文件中。 I am using the UNIX standard read() and write() calls to read in the input and write them to the file, however it seems to be running quite slowly because of how many of these calls there are. 我正在使用UNIX标准的read()和write()调用来读入输入并将它们写入文件,但是由于其中有许多调用,它似乎运行得很慢。

Here is the relevant code for reading: 以下是相关的阅读代码:

floats* input = make_floats(0); // input floats

int ifd = open(iname, O_RDONLY, 0644);

long count; // temp to get count

read(ifd, &count, sizeof(long)); // read in count

// read in numbers from input
for (int i = 0; i < count; ++i) {
    float num;

    read(ifd, &num, sizeof(float));

    floats_push(input, num);
}

it reads in the numbers one at a time into a float vector (that is the floats*). 它一次将数字读入一个浮点向量(即floats *)。

Here is the writing: 这是写作:

floats* xs = make_floats(0);
int ofd = open(args->output, O_WRONLY, 0644);
int xs_counter = 0;

// write the local array to file
for (int i = start; i < end; ++i) {
    write(ofd, &(xs->data[xs_counter]), sizeof(float));
    ++xs_counter;
}

start and end are the essentially how much I'm writing. 开始和结束本质上是我在写多少。 I'm wondering if I can essentially make these into a single mass read and write call, but I'm a little lost as to how (the code works fine btw it's just slow) 我想知道我是否基本上可以将它们做成一个整体的读写调用,但是我对如何操作却有些迷茫(代码运行得很好,但速度很慢)

Thanks 谢谢

Try replacing all those read calls with a single read: 尝试用单个读取替换所有这些读取调用:

float *numbers = malloc(sizeof(float) * count);
read(ifd, numbers, sizeof(float) * count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM