java – System. out. Print causes delay?

See the English answer > do not use system out. Println in server side code 9

package personal;

public class SpeedTest {
  public static void main(String[] args) {
    double DELAY = 5000;
    long startTime = System.currentTimeMillis();
    long endTime = (long)(startTime + DELAY);
    long index = 0;

    while (true) {
      double x = Math.sqrt(index);
      long Now = System.currentTimeMillis();
      if (Now >= endTime) {
        break;
      }
      index++;
    }
    System.out.println(index + " loops in " + (DELAY / 1000) + " seconds.");
  }
}@H_419_13@ 
 

这将在5.0秒内返回128478180个循环.

如果我添加System.out.println(x);在if语句之前,那么我在5秒内的循环次数下降到400,000s,这是由于System.out.println()中的延迟吗?或者只是在我没有打印出来的时候没有计算x?

Solution

Whenever you "output" in a very busy loop, regardless of any programming language, you will introduce two potentially important delays:

>The data must be converted to printable characters and then written to any display / device it may display... And... > "the act of outputting anything" forces the process to synchronize with any other process that may also produce output

An alternative strategy commonly used for this purpose is the tracking table This is a memory array with some fixed size and contains strings Entries are added to this table in a "Circular" manner: the oldest entries are constantly replaced by the latest entries This policy provides history without output (the only requirement left is that anyone who adds entries to or reads entries from the table must synchronize their activities, such as using mutexes.)

The process that wants to display the contents of the trace table should acquire the mutex, make a memory copy of the content of interest, and then release the mutex before preparing for output In this way, processes that provide entries to the trace table are not delayed by I / O related delay sources

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>