gpt4 book ai didi

java - system.nanoTime() 错误吗?

转载 作者:行者123 更新时间:2023-12-02 01:28:20 28 4
gpt4 key购买 nike

我正在编写一个 FTP 客户端应用程序,并在代码中的两个点使用了 System.nanoTime(),返回的秒数差异为 18,而我的程序只需要 2 秒...检查 onPostExecute 方法中的日志...为什么会发生这种情况以及如何解决?

protected String doInBackground(String... urls)
{
try
{
if(perflag)
return "Not yet";
String ipadd= ip.getText().toString();
BufferedReader br;
int port =Integer.parseInt(portt.getText().toString());
while(true) {
socket = new Socket(ipadd, port);
//Button conn=(Button) findViewById(R.id.connectb);
if(startflag)
{
starttime=System.nanoTime();
startflag=false;
}
//conn.setEnabled(false);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedOutputStream bo = new BufferedOutputStream(socket.getOutputStream());
PrintWriter pw = new PrintWriter(bo, true);
file = br.readLine();
if (file.equals("Finished"))
{
// socket.close();
Log.i("stat","above sock");
// Thread.sleep(1000);
//socket= new Socket(ipadd,port);
//br= new BufferedReader(new InputStreamReader(socket.getInputStream()));
datas=br.readLine();
data=Double.parseDouble(datas);
Log.i("stat",datas);
br.close();
socket.close();
finflag=true;
break;
}
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File f = new File(path, "/" + file);
byte[] buff = new byte[1024];
int len;

int i=0;
while(f.exists())
{
f= new File(path,"/"+"("+i+")"+file);
i++;
}
pw.println("done");
DataInputStream is = new DataInputStream(socket.getInputStream());
FileOutputStream fos = new FileOutputStream(f);
publishProgress(file);

while ((len = is.read(buff)) != -1) {


fos.write(buff, 0, len);

}

publishProgress(file);
}
}catch(NumberFormatException nfe)
{

runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
start();
}
});
nfe.printStackTrace();

}
catch(java.net.UnknownHostException un)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
start();
}
});
//Toast.makeText(MainActivity.this,"Enter a proper IP and port!",Toast.LENGTH_LONG).show();
un.printStackTrace();
}
catch(java.net.NoRouteToHostException no)
{

runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"There is no active server at the specified IP and port!",Toast.LENGTH_LONG).show();
start();
}
});
no.printStackTrace();
}
catch(Exception e)

{
Log.i("error",e.getMessage());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "Error occurred!Try checking storage permissions or connection.", Toast.LENGTH_LONG).show();

start();
}
});
e.printStackTrace();
}

endtime=System.nanoTime();
return "Not Yet";
}
protected void onProgressUpdate(String... para)
{
super.onProgressUpdate(para);
trans.setText("Transfering file: "+para[0]);
}
protected void onPostExecute(String as) {
start();

if(finflag)
{
startflag=true;
Log.i("start",String.valueOf(starttime));
Log.i("end",String.valueOf(endtime));
totaltime=endtime-starttime;

Log.i("total",String.valueOf(totaltime));
//totaltime/=100000000;
double time=totaltime/1000000000;
Log.i("time in secs",String.valueOf(time));
double rate= (double)(data/time);
Toast.makeText(MainActivity.this,"Transfer successful!",Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,"Average transfer rate: "+rate+"MBps",Toast.LENGTH_LONG).show();
finflag=false;
}
}

最佳答案

进行整数除法来获取秒数没有什么意义,因为这只会返回整秒;您不需要整秒使用nanoTime。变化:

double time=totaltime/1000000000;

double time=totaltime/1000000000d; // (or totaltime/1000000000.0)

但是你使用的除数没问题;纳米为 10-9。但是,我在您的代码中看到了一条注释掉的行,就在您的分区上方:

        //totaltime /= 100000000;
double time=totaltime/1000000000;

在那一行中,你的除数只有 8 个零,而不是 9 个零。您确定您发布的“18”秒来自 double time=totaltime/1000000000; 而不是来自 totaltime/= 100000000; 吗?因为如果除数中的 0 太少,则 1.8 秒的实际时间看起来就像 18 秒。

正如评论者所提到的,问题实际上是魔法常数,它很容易得到错误的零个数。

以下是解决此问题的几种方法:

  • Java 允许您出于任何原因在数字中添加下划线;您可以编写totaltime/1_000_000_000d,以便更清楚地看到您使用了多少个零。
  • Java 还允许使用科学记数法表示 double ,因此您也可以编写 totaltime/1e9
  • Java 内置了用于时间单位转换的函数;但是,由于您需要秒的几分之一,因此不能简单地说 TimeUnit.NANOSECONDS.toSeconds(totaltime) (它会向下舍入到 1 秒)。但是,您可以说 totaltime/(double) TimeUnit.SECONDS.toNanos(1)

关于java - system.nanoTime() 错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56511072/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com