且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测量下载速度 Java

更新时间:2023-02-10 15:52:11

与衡量任何事物的方式相同.

The same way you would measure anything.

System.nanoTime() 返回一个 Long,你可以用它来衡量某件事需要多长时间:

System.nanoTime() returns a Long you can use to measure how long something takes:

Long start = System.nanoTime();
// do your read
Long end = System.nanoTime();

现在您获得了读取 X 字节所需的纳秒数.算一算,你就有了下载率.

Now you have the number of nanoseconds it took to read X bytes. Do the math and you have your download rate.

您很可能正在寻找每秒字节数.跟踪您已阅读的总字节数,检查是否已过去一秒钟.一秒过去后,根据您在这段时间内读取的字节数计算出速率.重置总数,重复.

More than likely you're looking for bytes per second. Keep track of the total number of bytes you've read, checking to see if one second has elapsed. Once one second has gone by figure out the rate based on how many bytes you've read in that amount of time. Reset the total, repeat.