2016-03-07 62 views
1

我使用此代碼實時打開一個記錄文件,並使用FSEEK()和FTELL文件大小(),以獲得文件大小:幫助優化函數來獲取在一個循環

typedef struct _Recording Recording; 
struct _Recording 
{ 
    FILE *file; 
    long filesize; 
    int progress_id; 
    ... 
}; 

void start_recording(Recording *recording, char* filepath) 
{ 
     ...   
     recording->file = fopen(filepath, "rb"); 
     recording->progress_id = 
      g_timeout_add (500, (GSourceFunc) progress_timeout, recording); 
} 

gboolean progress_timeout (Recording *recording) 
{ 
     if (recording->file != NULL) 
     { 
      fseek(recording->file, 0, SEEK_END); 
      recording->filesize = ftell(recording->file);   
     } 

     return TRUE; 
} 

void stop_recording(Recording *recording) 
{ 
     ... 
     if (recording->file) 
     { 
      fclose (recording->file); 
      recording->file = NULL; 
     } 

     if (recording->progress_id != 0) 
     { 
      g_source_remove (recording->progress_id); 
      recording->progress_id = 0; 
     } 
} 

我使用這個函數在一個循環中(500毫秒)。需要幫助來優化功能才能更快。

代碼的效率。

與循環功能

+0

(與代碼無關,但是..)你使用什麼編譯器?試試'gcc -O3'。 –

+0

詳細信息:使用'long filesize;' – chux

+3

更好使用[fstat](http://linux.die.net/man/2/fstat) – chux

回答

3

更新。如果你不要求提供「最大」(questioned)的兼容性,是有意義的像fstatuse operating system specific功能。打開一個文件總是會有開銷,甚至尋找到最後 - 操作系統試圖預測你正在做什麼,並可能開始將文件內容緩存到內存中 - 在這種情況下是不必要的。

2

代碼訪問文件系統;文件系統和物理磁盤訪問的性能將佔主導地位。此外,大部分執行的代碼都是操作系統和文件系統代碼,而不是你自己的代碼,因此不需要對代碼進行優化就可以提供幫助。

使用較低級別或操作系統特定的API而不是stdio可能會帶來一些邊際收益,例如,用於POSIX的stat()fstat()或用於Windows的GetFileSizeEx()。這些直接得到的大小,而不是使用fseek()所以可能會更快,但可能不是因爲給出的原因顯着。