2011-01-29 9 views
2

Dropboxへのファイルアップロードの速度を計算したいと思います。アップロードされたパーセンテージからアップロード速度を取得

は、ここで私が現在使用しているコードです:

int numberOfCalls = 0; 

- (float)getUploadSpeed:(float)currentAmountUploaded { 
    numberOfCalls++; 
    NSLog(@"called %d times.", numberOfCalls); 
    NSLog(@"speed approx. %fKB/sec.", (currentAmountUploaded/numberOfCalls)*1024); 
    return (currentAmountUploaded/numberOfCalls)*1024; 
} 

- (void)startUploadSpeedTest:(NSNumber *)uploadCurrent { 

    float uploadedFileSize = [uploadCurrent floatValue]; 

    NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:@selector(getUploadSpeed:)]; 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
    [invocation setSelector:@selector(getUploadSpeed:)]; 

    [invocation setTarget:self]; 
    [invocation setArgument:&uploadedFileSize atIndex:2]; 
    [invocation invoke]; 

    NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; 

    [[NSTimer timerWithTimeInterval:1.0 invocation:invocation repeats:YES] retain]; 

    [runLoop run]; 
    [pool release]; 
} 

- (void)restClient:(DBRestClient *)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath { 
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:srcPath error:nil]; 
    float fileSize = ((float)[fileAttributes fileSize]/1024/1024); 
    float uploadedFileSize = fileSize * progress; 

    NSNumber *number = [[[NSNumber alloc] initWithFloat:uploadedFileSize] autorelease]; 

    NSThread *timerThread = [[[NSThread alloc] initWithTarget:self selector:@selector(startUploadSpeedTest:) object:number] autorelease]; 
    [timerThread start]; 
} 

ただし、タイマーは秒ごとに呼び出されていない、と私は、これはスピードを得るための最良の方法であるか分かりません。

助けてください。

答えて

4

uploadProgress-Methodでスピードを直接計算してみませんか?

これは非常に簡単な解決方法です。

-(void) restClient:(DBRestClient *)client uploadProgress:(CGFloat)progress forFile:(NSString *)destPath from:(NSString *)srcPath { 
    static NSDate* date = nil; 
    static double oldUploadedFileSize = 0; 
    if (!date) { 
     date = [[NSDate date] retain]; 
    } else { 
     NSTimeInterval sec = -[date timeIntervalSinceNow]; 
     [date release]; 
     date = [[NSDate date] retain]; 
     NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:srcPath error:nil]; 
     double uploadedFileSize = (double)[fileAttributes fileSize] * progress; 
     if (sec) { 
      NSLog(@"speed approx. %.2f KB/s", (uploadedFileSize - oldUploadedFileSize)/1024.0/sec); 
     } 
     oldUploadedFileSize = uploadedFileSize; 
    } 

} 

注意してください、最初と最後の速度値が不正確かもしれません。

+0

ありがとうございました!それを動作させる方法を理解できませんでした! –

関連する問題