Home > Blockchain >  Performance of for loop in golang
Performance of for loop in golang

Time:01-29

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.

CodePudding user response:

main.go

package main

import (
    "fmt"
    "io/ioutil"
    "math"
    "net/http"
    "time"
)

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
}

var testInputFile = "https://gist.githubusercontent.com/uprety/28f618cf04f2ced64c15c02249df14a4/raw/a3f7692a0e9c95523fc262b5c357d1cf6bd2879d/testfile.in"

func main() {
    // download test input
    resp, err := http.Get(testInputFile)
    if err != nil {
        panic(err)
    }
    input, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    inputString := string(input)
    fmt.Println("Length of input:", len(inputString))
    start := time.Now()
    fmt.Println("largeInverseFactorial result:", largeInverseFactorial(inputString))
    fmt.Println("takes", time.Since(start).Seconds(), "seconds")
}

TEST RESULT:

> go run main.go
Length of input: 920443
largeInverseFactorial result: 189999
takes 0.0023581 seconds
  •  Tags:  
  • Related