簡體   English   中英

在C中加快許多UNIX讀/寫調用的速度

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

我正在編寫一個程序(警告,這是一個家庭作業問題),它將對作為輸入文件接收的5000萬浮點數進行排序,並將其輸出到另一個文件中。 我正在使用UNIX標准的read()和write()調用來讀入輸入並將它們寫入文件,但是由於其中有許多調用,它似乎運行得很慢。

以下是相關的閱讀代碼:

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);
}

它一次將數字讀入一個浮點向量(即floats *)。

這是寫作:

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;
}

開始和結束本質上是我在寫多少。 我想知道我是否基本上可以將它們做成一個整體的讀寫調用,但是我對如何操作卻有些迷茫(代碼運行得很好,但速度很慢)

謝謝

嘗試用單個讀取替換所有這些讀取調用:

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