How to correctly measure NSInputStream data rate

673 Views Asked by At

I'm trying to measure actual transfer speed during ftp download, download itself is working, streams are hooked up in run loop. Measurment is done in NSStreamEventHasBytesAvailable using CFTimeGetCurrent on event start and at the end, after data is written to file elapsed time is computed with (double)previousTimestamp-CFAbsoluteTimeGetCurrent, but the time I get is absolutely unreasonable. Tested on simulator and device, can anyone enlighten me?

code:

    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();
1

There are 1 best solutions below

3
On

An alternative that I have used is to use the time.h and c routines to capture time.

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

Another good link on SO iPhone: How to get current milliseconds?