Faster input scanning

前端 未结 3 1365
清酒与你
清酒与你 2020-12-06 17:28

I am attempting to solve the SPOJ question that can be found here

Following is my solution:

package main

import \"fmt\"
import \"bufio\"
import \"os         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 18:07

    I coded 3 versions to compare them. The first using fmt.Scanf("%d", &v), the second converting numbers from bytes (like @icza), and the third converting using strconv.Atoi. To use the functions I initializated scanner in that way:

    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords)
    

    So, every time I call scanner.Scan, it returns a token splitted by spaces. And the functions follow:

    func scanFromBytes(scanner *bufio.Scanner) (n int) {
        scanner.Scan()
    
        buf := scanner.Bytes()
        for _, v := range buf {
            n = n*10 + int(v-'0')
        }
    
        return
    }
    

    And:

    func scanAtoi(scanner *bufio.Scanner) (n int) {
        scanner.Scan()
        
        n, _ = strconv.Atoi(scanner.Text())
    
        return
    }
    

    I have tested with a big file (40k tests), reading about 8 integers per test. The fmt.Scanf solution, takes about 1.9s, as expected (more than the others). In the two functions I got about 0.8s. But the scanAtoi always takes about 0.05s less than scanFromBytes, except for the very first time (maybe some caching occurs).

提交回复
热议问题