我想计算文件上传到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];
}
但是,定时器不会每秒调用一次,我不确定这是获得速度的最佳方法。
任何帮助表示感谢。
答案 0 :(得分: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;
}
}
注意,第一个和最后一个速度值可能不准确。