Home > Backend Development > Golang > How Can I Optimize Input Scanning in Go for Faster Integer Extraction?

How Can I Optimize Input Scanning in Go for Faster Integer Extraction?

DDD
Release: 2024-12-14 15:45:18
Original
285 people have browsed it

How Can I Optimize Input Scanning in Go for Faster Integer Extraction?

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template