why golang is so slow, it takes 150 ms in average?


  • 0
    T

    shouldn't it be faster than python?


  • 0
    T

  • 0

    You can paste your code here to evaluate.

    Moreover, the distribution graph is more useful when to compare the solution to others which are of the same language.

    We treat languages differently when judge, perhaps your golang solution runs 100 times and python run only 10 times. That's possible.


  • 0
    Y

    I wrote with Python and Golang, which is both straightforward solution.
    Run in LeetCode:
    Golang: 165 ms, beats 95.19%
    Python: 86 ms, beats 47.08 %

    I measured the performance in my desktop with changing the N
    N=10^5, Golang: 4.13 ms, Python: 41.4ms
    N=10^6, Golang: 51.3 ms, Python: 292ms
    N=10^7, Golang: 486 ms, Python: 2540ms

    So as @xidui noticed, it's just that that how the LeetCode measures the performance differs in each language.

    The rest is the code i used:
    Python 2.7.13
    Go 1.7.5

    Python:

    import time
    
    def sub(n):
      for i in xrange(1, n + 1):
        isThree = i % 3 == 0
        isFive = i % 5 == 0
        if isThree and isFive:
          yield "FizzBuzz"
        elif isThree:
          yield "Fizz"
        elif isFive:
          yield "Buzz"
        else:
          yield str(i)
    
    
    def main():
      prev = time.time()
      x = list(sub(100000))[-1]
      cur = time.time()
      print cur - prev, x
    
    
    if __name__ == "__main__":
      main()
    

    Golang:

    package main
    
    import (
    	"fmt"
    	"strconv"
    	"time"
    )
    
    func fizzBuzz(n int) []string {
    	r := make([]string, n)
    	for i := 1; i <= n; i++ {
    		isThree := i%3 == 0
    		isFive := i%5 == 0
    		switch {
    		case isThree && isFive:
    			r[i-1] = "FizzBuzz"
    		case isThree:
    			r[i-1] = "Fizz"
    		case isFive:
    			r[i-1] = "Buzz"
    		default:
    			r[i-1] = strconv.Itoa(i)
    		}
    	}
    	return r
    }
    
    func main() {
    	prev := time.Now()
    	result := fizzBuzz(10000000)
    	cur := time.Now()
    	fmt.Println(cur.Sub(prev), result[len(result)-1])
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.