从Java中读取System.in的最快方法是什么?

问题描述 投票:56回答:6

我正在阅读使用Scanner(System.in)标准中由空格或换行符分隔的一堆整数。

有没有更快的方法在Java中这样做?

java optimization inputstream stdin
6个回答
84
投票

有没有更快的方法在Java中这样做?

是。扫描仪相当慢(至少根据我的经验)。

如果您不需要验证输入,我建议您将流包装在BufferedInputStream中并使用类似String.split / Integer.parseInt的内容。


一个小比较:

使用此代码读取17兆字节(4233600个数字)

Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
    sum += scanner.nextInt();

拿了我的机器3.3秒。而这个片段

BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = bi.readLine()) != null)
    for (String numStr: line.split("\\s"))
        sum += Integer.parseInt(numStr);

花了0.7秒。

通过进一步搞乱代码(用line / String.indexOf迭代String.substring)你可以很容易地将它降低到大约0.1秒,但我想我已经回答了你的问题,我不想把它变成一些高尔夫代码。


3
投票

我创建了一个小型的InputReader类,它的工作方式与Java的Scanner类似,但速度超过了它的许多幅度,实际上它也优于BufferedReader。这是一个条形图,显示我创建的InputReader类的性能,从标准输入读取不同类型的数据:

enter image description here

以下是使用InputReader类查找来自System.in的所有数字之和的两种不同方法:

int sum = 0;
InputReader in = new InputReader(System.in);

// Approach #1
try {

    // Read all strings and then parse them to integers (this is much slower than the next method).
    String strNum = null;
    while( (strNum = in.nextString()) != null )
        sum += Integer.parseInt(strNum);

} catch (IOException e) { }

// Approach #2
try {

    // Read all the integers in the stream and stop once an IOException is thrown
    while( true ) sum += in.nextInt();

} catch (IOException e) { }

3
投票

如果从竞争性编程的角度提出要求,如果提交的速度不够快,那将是TLE。 然后,您可以检查以下方法以从System.in检索String。我从java(竞争网站)中最好的编码器之一

private String ns()
{
    int b = skip();
    StringBuilder sb = new StringBuilder();
    while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
        sb.appendCodePoint(b);
        b = readByte();
    }
    return sb.toString();
}`

1
投票

您可以通过数字方式从System.in读取。看看这个答案:https://stackoverflow.com/a/2698772/3307066

我在这里复制代码(几乎没有修改过)。基本上,它读取整数,由任何不是数字的东西分隔。 (致原作者的信誉。)

private static int readInt() throws IOException {
    int ret = 0;
    boolean dig = false;
    for (int c = 0; (c = System.in.read()) != -1; ) {
        if (c >= '0' && c <= '9') {
            dig = true;
            ret = ret * 10 + c - '0';
        } else if (dig) break;
    }
    return ret;
}

在我的问题,这个代码是约。比使用StringTokenizer快2倍,String.split(" ")已经比StringTokenizer快。 (问题涉及读取100万个整数,每个整数高达100万。)


1
投票

String str = input.readLine(); //read string of integers using BufferedReader e.g. "1 2 3 4" List<Integer> list = new ArrayList<>(); StringTokenizer st = new StringTokenizer(str, " "); while (st.hasMoreTokens()) { list.add(Integer.parseInt(st.nextToken())); } 是一种更快速的读取由令牌分隔的字符串输入的方法。

检查下面的示例以读取由空格分隔的整数字符串并存储在arraylist中,

import java.io.InputStream;
import java.util.InputMismatchException;
import java.io.IOException;

public class Scan
{

private byte[] buf = new byte[1024];

private int total;
private int index;
private InputStream in;

public Scan()
{
    in = System.in;
}

public int scan() throws IOException
{

    if(total < 0)
        throw new InputMismatchException();

    if(index >= total)
    {
        index = 0;
        total = in.read(buf);
        if(total <= 0)
            return -1;
    }

    return buf[index++];
}


public int scanInt() throws IOException
{

    int integer = 0;

    int n = scan();

    while(isWhiteSpace(n))   /*  remove starting white spaces   */
        n = scan();

    int neg = 1;
    if(n == '-')
    {
        neg = -1;
        n = scan();
    }

    while(!isWhiteSpace(n))
    {

        if(n >= '0' && n <= '9')
        {
            integer *= 10;
            integer += n-'0';
            n = scan();
        }
        else
            throw new InputMismatchException();
    }

    return neg*integer;
}


public String scanString()throws IOException
{
    StringBuilder sb = new StringBuilder();

    int n = scan();

    while(isWhiteSpace(n))
        n = scan();

    while(!isWhiteSpace(n))
    {
        sb.append((char)n);
        n = scan();
    }

    return sb.toString();
}


public double scanDouble()throws IOException
{
    double doub=0;
    int n=scan();
    while(isWhiteSpace(n))
    n=scan();
    int neg=1;
    if(n=='-')
    {
        neg=-1;
        n=scan();
    }
    while(!isWhiteSpace(n)&& n != '.')
    {
        if(n>='0'&&n<='9')
        {
            doub*=10;
            doub+=n-'0';
            n=scan();
        }
        else throw new InputMismatchException();
    }
    if(n=='.')
    {
        n=scan();
        double temp=1;
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                temp/=10;
                doub+=(n-'0')*temp;
                n=scan();
            }
            else throw new InputMismatchException();
        }
    }
    return doub*neg;
}

public boolean isWhiteSpace(int n)
{
    if(n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1)
        return true;

    return false;
}

public void close()throws IOException
{
    in.close();
}
}

0
投票

在编程方面,这个定制的Scan和Print类比Java内置的Scanner和BufferedReader类更好。

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class Print
{
private BufferedWriter bw;

public Print()
{
    this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}


public void print(Object object)throws IOException
{
    bw.append("" + object);
}

public void println(Object object)throws IOException
{
    print(object);
    bw.append("\n");
}


public void close()throws IOException
{
    bw.close();
}

}

定制的Print类可以如下所示

BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
  int t = Integer.parseInt(inp.readLine());
  while(t-->0){
    int n = Integer.parseInt(inp.readLine());
    int[] arr = new int[n];
    String line = inp.readLine();
    String[] str = line.trim().split("\\s+");
    for(int i=0;i<n;i++){
      arr[i] = Integer.parseInt(str[i]);
    }

0
投票

您可以使用BufferedReader读取数据

    StringBuffer sb = new StringBuffer();
    for(int i=0;i<n;i++){
              sb.append(arr[i]+" "); 
            }
    System.out.println(sb);

而对于打印使用StringBuffer

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.