'Performance of fmt.Scanf() in golang
I am trying to implement my python code in go. Here is a python code to find the inverse factorial of a large digit.
def largeInverseFactorial(n):
len_n = len(n)
i = 1
ans = 1
while True:
ans += math.log10(i)
if ans >= len_n:
return i
i += 1
Here is the go code after translating:
func largeInverseFactorial(n string) int64 {
len_n := float64(len(n))
var i float64 = 1
var ans float64 = 1
for true {
ans += math.Log10(i)
if ans >= len_n {
return int64(i)
}
i += 1
}
return 0
}
I need this go code to work with string of digits where its length can go up to 10^6. But to my surprise the go code is more than 20 times slower than its python counterpart. Can anybody tell me what am I missing in go or what's the reason behind it.
Update: The problem seems on the other side. So after using bufio.NewReader(os.Stdin).ReadString('\n') the code worked well and there is no wrong in for loop which was my original thought. Here is the code it worked:
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
)
func smallInverseFactorial(value string) int64 {
var pre, ans int64
pre = 1
ans = 1
intVal, _ := strconv.ParseInt(value, 10, 64)
if intVal == 1 {
return 1
}
for ans < intVal {
ans *= pre
pre += 1
}
return pre - 1
}
func largeInverseFactorial(n string) int64 {
len_n := float64(len(n))
var i float64 = 1
var ans float64 = 1
for {
ans += math.Log10(i)
if ans >= len_n {
return int64(i)
}
i += 1
}
return 0
}
func main() {
var value string
value, _ = bufio.NewReader(os.Stdin).ReadString('\n')
value = strings.Split(value, "\n")[0]
// fmt.Scanf("%s", &value)
if len(value) < 3 {
fmt.Println(smallInverseFactorial(value))
} else {
fmt.Println(largeInverseFactorial(value))
}
}
So my question why using fmt.Scanf() is super slow when input gets larger?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
