Optimizing Input Scanning for Performance
In response to a question seeking to optimize input reading speed, it is recommended to consider using bufio.Scanner over fmt.Scan. However, even with bufio, a timeout issue persists.
To address this issue, replacing fmt.Scan with bufio.Scanner and utilizing a custom conversion function to efficiently extract integers from the raw bytes can significantly improve input reading performance. Here's the optimized solution:
package main import ( "bufio" "fmt" "os" ) func main() { var n, k, c int scanner := bufio.NewScanner(os.Stdin) scanner.Scan() fmt.Sscanf(scanner.Text(), "%d %d", &n, &k) for ; n > 0; n-- { scanner.Scan() if toInt(scanner.Bytes())%k == 0 { c++ } } fmt.Println(c) } func toInt(buf []byte) (n int) { for _, v := range buf { n = n*10 + int(v-'0') } return }
This revised code uses bufio.Scanner to read lines of input, optimizing efficiency by directly parsing numbers from bytes instead of converting to strings unnecessarily. As a result, the solution achieves a notable performance boost compared to other methods.
The above is the detailed content of How Can I Optimize Input Scanning in Go for Faster Integer Extraction?. For more information, please follow other related articles on the PHP Chinese website!