1GBなどの大容量ファイルの場合、wc -l
非常に遅くなります。特定のファイルの改行数を数えるより速い方法はありますか?
ベストアンサー1
あなたは試すことができますCで書く:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(){
char buf[BUFSIZ];
int nread;
size_t nfound=0;
while((nread=read(0, buf, BUFSIZ))>0){
char const* p;
for(p=buf; p=memchr(p,'\n',nread-(p-buf)); nfound++,p++) {;}
}
if(nread<0) { perror("Error"); return 1; }
printf("%lu\n", nfound);
return 0;
}
たとえば、wcl.c
コンパイル、たとえば、gcc wcl.c -O2 -o wcl
実行して保存します。
<yourFile ./wcl
これは私のシステムで改行文字でいっぱいの1GBファイルを見つけました。370ミリ秒(実行を繰り返す)。 (バッファサイズを増やすと時間が少し増えますが、これは予想通りです。BUFSIZは最適値に近いはずです)。380ミリ秒私はから来ましたwc -l
。
Mmapingでより良い時間を過ごしました。280ミリ秒しかし、もちろん、実際のファイルに制限される制限があります(FIFOなし、端末入力なしなど)。
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
struct stat sbuf;
if(fstat(0, &sbuf)<0){ perror("Can't stat stdin"); return 1; }
char* buf = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, 0/*stdin*/, 0/*offset*/);
if(buf == MAP_FAILED){ perror("Mmap error"); return 1; }
size_t nread = sbuf.st_size, nfound=0;
char const* p;
for(p=buf; p=memchr(p,'\n',nread-(p-buf)); nfound++,p++) {;}
printf("%lu\n", nfound);
return 0;
}
次のコマンドを使用してテストファイルを作成しました。
$ dd if=/dev/zero of=file bs=1M count=1042
いくつかのテスト改行を追加しました。
$ echo >> 1GB
そして16進エディタ。