Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

objective c - Calculating Connection/Download Speed

I have a client and server program (both in Obj-C) and I am transferring files between two devices using the programs.

The transferring is working fine, but I would like to display to the user what transfer rate they are getting.

So I know the total size of the file, and how much of the file has been transferred, is there a way to figure out the transfer rate from this information, and if not, what information do I need to calculate the transfer rate?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The na?ve way is bytes_downloaded / (now - start_time), but that becomes inaccurate if the connection speed fluctuates wildly, or if the user starts another download (perhaps in another app) halfway through your download. Both of these may happen if the user runs a torrent in the background.

A better way (though harder to implement) is to keep an array of periodic samples and present the average.

Start out with an array containing 0. The array is of samples, and each sample is the number of bytes downloaded since the previous sample. Then start the download.

Every half-second (you can try different intervals), measure how many bytes you've downloaded, then subtract the previous total from this new total. Add the difference as the new last element?in the array. If this grows the array beyond a certain size, lop off the first element (oldest sample). Then, present the average of all the samples.

You should keep somewhere between 2–5 seconds' worth of samples, and the interval should be somewhere between 0.5 and 1 seconds (it's a trade-off between currency and performance).

You may also want to remove the first element from the array after retrieving it if it is zero. This makes your starting reportage more accurate and helps you recover more quickly from stalls, since you're not including old zeroes in the average.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...