我正在编写一个FTP客户端应用程序,并在代码中的两点使用了System.nanoTime(),以秒为单位的差异返回为18,而我的程序只需要2 seconds...Check 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;
}
}发布于 2019-06-09 10:33:09
tl;dr
Duration // Represent a span-of-time unattached to the timeline.
.ofNanos( // Represent a count of nanoseconds.
System.nanoTime() - start // Calculate elapsed nanoseconds.
) // Returns a `Duration` object.
.toString() // Generates text in standard ISO 8601 format for elapsed time.PT2.020615864S
Duration
我会使用Duration类。此类表示未附加到时间线的时间跨度,分辨率为小时-分钟-秒-纳秒。
将调用System.nanoTime返回的两个nanoseconds计数相减。将结果传递给Duration.ofNanos。
long start = System.nanoTime() ;
Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) );
long stop = System.nanoTime() ;
Duration d = Duration.ofNanos( stop - start ) ;
System.out.println( d ) ;请参阅此code run live at IdeOne.com。
PT2.020615864S
实际上,在实际代码中,我们需要处理Thread sleep被中断(唤醒)。
long start = System.nanoTime();
try
{
Thread.sleep( TimeUnit.SECONDS.toMillis( 2 ) );
} catch ( InterruptedException e )
{
e.printStackTrace();
}
long stop = System.nanoTime();
Duration d = Duration.ofNanos( stop - start );
System.out.println( d );https://stackoverflow.com/questions/56511072
复制相似问题