2

我正在尝试测量 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();
4

1 回答 1

1

我使用的另一种方法是使用 time.h 和 c 例程来捕获时间。

http://www.cplusplus.com/reference/clibrary/ctime/time/

SO iPhone 上的另一个好链接 :如何获取当前毫秒数?

于 2012-06-02T01:54:44.507 回答