質問
私はソフトウェアのファイルのダウンロードに取り組んでいます。これは私が手に入れたものであり、それは責任を持ってダウンロードします。ダウンロード速度を測定します。私はあなたの助けに感謝します。ありがとう。これは、現在のダウンロードメソッドコードです
public void run()
{
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try
{
URL url1 = new URL(url);
out = new BufferedOutputStream(
new FileOutputStream(sysDir+"\\"+where));
conn = url1.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
double progress1;
while ((numRead = in.read(buffer)) != -1)
{
out.write(buffer, 0, numRead);
numWritten += numRead;
this.speed= (int) (((double)
buffer.length)/8);
progress1 = (double) numWritten;
this.progress=(int) progress1;
}
}
catch (Exception ex)
{
echo("Unknown Error: " + ex);
}
finally
{
try
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
catch (IOException ex)
{
echo("Unknown Error: " + ex);
}
}
}
解決
同じ方法で、何でも測定します。
System.nanoTime()
返品a Long
何かにかかる時間を測定するために使用できます。
Long start = System.nanoTime();
// do your read
Long end = System.nanoTime();
これで、Xバイトを読み取るのに必要なナノ秒数が得られます。数学を行うと、ダウンロード率があります。
おそらくあなたは毎秒バイトを探しています。読んだバイトの総数を追跡し、1秒が経過しているかどうかを確認します。その時間で読んだバイトの数に基づいて、1秒がレートを把握することができます。合計をリセットして、繰り返します。
他のヒント
これが私の実装です
while (mStatus == DownloadStatus.DOWNLOADING) {
/*
* Size buffer according to how much of the file is left to
* download.
*/
byte buffer[];
// handled resume case.
if ((mSize < mDownloaded ? mSize : mSize - mDownloaded <= 0 ? mSize : mSize - mDownloaded) > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (mSize - mDownloaded)];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;// EOF, break while loop
// Write buffer to file.
file.write(buffer, 0, read);
mDownloaded += read;
double speedInKBps = 0.0D;
try {
long timeInSecs = (System.currentTimeMillis() - startTime) / 1000; //converting millis to seconds as 1000m in 1 second
speedInKBps = (mDownloaded / timeInSecs) / 1024D;
} catch (ArithmeticException ae) {
}
this.mListener.publishProgress(this.getProgress(), this.getTotalSize(), speedInKBps);
}
私はあなたに一般的なアイデアを与えることができます。ダウンロードの先頭にタイマーを開始します。さて、を掛けます (percentage downloaded)
によって download size
, 、そしてそれをで分割します time elapsed.
これにより、平均ダウンロード時間が得られます。私があなたを正しい軌道に乗せることを願っています!
使用できます System.nanoTime();
ブライアンが示唆しているように。
置く long startTime = System.nanoTime();
あなたのwhileループの外。と
long estimatedTime = System.nanoTime() - startTime;
ループ内の経過時間を与えます。
所属していません StackOverflow