※ 引述《mself (mself)》之銘言:
: Linux + GCC
: 問題(Question):
: 我寫一個程式,主體是一個迴圈並且從檔案中讀取資料來處理。例如:
: while(fin.good()){
: fin >> time;
: fin >> voltage;
: subfunction(time, voltage);
: }
: 餵入的資料(Input):
: 0000 1.5
: 我有聽說最好把 file I/O 集中,一次讀一批會比較快
: 不曉得大概是怎麼做?
: 謝謝~
可以考慮用 memory map file. mmap function
摘錄說明如下.
The mmap() function establishes a mapping between a process' address space and
a file or shared memory object. The format of the call is as follows:
pa=mmap(addr, len, prot, flags, fildes, off);
The mmap() function allows access to resources via address space manipulations,
instead of read()/write(). Once a file is mapped, all a process has to do to
access it is use the data at the address to which the file was mapped. So,
using pseudo-code to illustrate the way in which an existing program might
be changed to use mmap(), the following:
fildes = open(...)
lseek(fildes, some_offset)
read(fildes, buf, len)
/* use data in buf */
becomes:
fildes = open(...)
address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset)
/* use data at address */
拿到 address之後, 就可以開始存取, 檔案內容會出現在 address 所指的記憶體
位置裡.
你可以用 sscanf 來讀, 當然也可以自己寫個 parser 來讀.
用完記得用 munmap 來解除 mapping.
這應該是最節省 CPU時間的方法.
--
Do not depend on others without effort...
當我年輕時,請教別人問題時常聽到上面那句話. 當時心裏偶而會有些小小抱怨.
當時間過去,我偶而會想到上面那句話, 心中十分感謝當初告訴我那句話的人.
當發現問題時,最有價值的不是問題的答案,
而是找到解決的方向,並在努力的過程裡具備解決問題的能力.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 221.169.44.139