我正在尝试测量ftp下载期间的实际传输速度,下载本身正在工作,流在运行循环中连接。在事件开始时使用CFTimeGetCurrent在NSStreamEventHasBytesAvailable中进行测量,最后,在将数据写入文件之后,使用(double)previousTimestamp-CFAbsoluteTimeGetCurrent计算经过的时间,但是我得到的时间绝对不合理。在模拟器和设备上测试过,任何人都可以启发我吗?
代码:
switch (eventCode) {
case NSStreamEventOpenCompleted: {
} break;
case NSStreamEventHasBytesAvailable: {
if ([[self.fileStream propertyForKey:NSStreamFileCurrentOffsetKey] intValue]==0) {
previousTimestamp = CFAbsoluteTimeGetCurrent();
}
NSInteger bytesRead;
uint8_t buffer[32768];
bytesRead = [self.networkStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == -1)
{
[self _stopReceiveWithStatus:@"Err"];
}
else if (bytesRead == 0)
{
[self _stopReceiveWithStatus:nil];
}
else
{
[self completition:bytesRead];
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
// Write to the file.
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&buffer[bytesWrittenSoFar] maxLength:bytesRead - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self _stopReceiveWithStatus:@"File err"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != bytesRead);
[self downloadSpeedSave:bytesRead :previousTimestamp-CFAbsoluteTimeGetCurrent()];
previousTimestamp = CFAbsoluteTimeGetCurrent();
答案 0 :(得分:1)
我使用的另一种方法是使用time.h和c例程来捕获时间。
http://www.cplusplus.com/reference/clibrary/ctime/time/
关于SO的另一个好的链接 iPhone: How to get current milliseconds?