2013-03-10 24 views
0

我正在尋找建議/如何創建一個逗號分隔的日誌文件在iPhone上的實現當我的數據以相對較快的速度(每次200次第二)。我期望捕獲每個數據點的時間戳和2-3個整數。在15分鐘內,會有15 * 60 * 200 = 180,000行數據,每個數據都有一個時間戳,一些整數和一個換行符。iOS iPhone尋找快速記錄時間戳整數數據文件執行

我想確保將這些數據寫入磁盤的順序是正確的。

我目前的實施已針對每秒鐘以1個數據點進入的數據進行了優化,對於「快速」數據可能效率不高。 如何調整我的代碼以確保它可以在後臺線程中運行,而不會爲每次寫入佔用太多資源?另外,是否有一個快速的「登錄到數據文件」的實現,我可以給它一個數字並在稍後要求它提供一個日誌文件?

NSString *appDataFile ; 
    NSFileHandle *aFileHandle; 

-(NSString*)dataFilePath 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    appDataFile = [documentsDirectory stringByAppendingPathComponent:@"Data"]; 
    aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile]; 
    return appDataFile; 
} 

//creates a new log file for each app run, or appends to existing log 
-(void)writeStringToDataFile:(NSString *)csvLine 
{ 

    if(aFileHandle) 
    { 
     //telling aFilehandle what file write to 
     [aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file 
     [aFileHandle writeData:[csvLine dataUsingEncoding:NSUTF8StringEncoding]]; 

    }else{ 
     NSData* headers = [@"timestamp,waveform amplitude,score, connection, event\n" dataUsingEncoding:NSUTF8StringEncoding]; 

     //clear the old log file 
     NSError *error = nil; 
     NSFileManager* fileManager = [NSFileManager defaultManager]; 
     [fileManager removeItemAtPath:[self dataFilePath] error:&error]; 

     //create CSV headers 
     aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile]; 
     [headers writeToFile:appDataFile atomically:YES]; 

     aFileHandle = [NSFileHandle fileHandleForWritingAtPath:appDataFile]; 
     //telling aFilehandle what file write to 
     [aFileHandle truncateFileAtOffset:[aFileHandle seekToEndOfFile]]; //setting aFileHandle to write at the end of the file 
     [aFileHandle writeData:[csvLine dataUsingEncoding:NSUTF8StringEncoding]]; 

    } 

} 
+1

怎麼樣:用NSArray將數據存儲在內存中。然後使用後臺線程繼續從NSArray檢索數據,並將其寫入文件。這將很容易實施和維護?你可以創建一個先進先出隊列,這樣你就不會用完內存 – vodkhang 2013-03-10 01:25:58

+0

謝謝你的建議。我目前有一個〜600個數據點的循環數組,用於以1 /秒進入的數據,並且每2分鐘使用數組索引實現自動保存數據的自動保存。使用普通數組需要太多內存(在快速記錄的情況下高達21 Mb) – 2013-03-11 14:34:17

回答

2

一個明顯的變化是去掉不必要的調用截斷該文件爲你想要寫的每一行。當您打開文件時,只需將句柄移動到最後一次。

下一輪更改將使用C代碼而不是Objective-C。使用fopen打開文件。使用fputs編寫一個C字符串。

另一個需要檢查的地方是如何構建csvLine。使用stringWithFormat很慢。使用fputs獲取低電平並將每個單獨值寫爲C字符串。無需格式化。無需轉換爲NSData。

也看看你如何做時間戳。如果將NSDate轉換爲NSString,則會浪費大量時間。

下面是一個很大的建議 - 如果時間如此重要,那麼在內存中創建一個大的可變字符串,然後在完成時將整個文件寫入一個文件。這將在時間關鍵階段切斷文件I/O。

利用儀器找出真正的瓶頸所在。沒有它你可以優化錯誤的代碼。