doute7910 2018-06-03 11:57
浏览 24
已采纳

阵列大小对性能的影响

I just started learning Go and I found myself creating a simple program that:

  • Creates an int array of size SIZE (expected to be >= 1000)
  • Iterates through its elements from 0 to 999, setting them to 0
  • Prints how long everything took

Something like this:

package main

import (
    "time"
    "fmt"
)

const SIZE = 1000

func main() {
    start := time.Now()
    a := [SIZE]int {}
    for i := 0; i < 1000; i++ { a[i] = 0 }
    fmt.Println("Time: ", time.Since(start))
}

I got the following results after running on my machine 5 times:

  • 3.375µs
  • 2.831µs
  • 2.698µs
  • 2.655µs
  • 2.59µs

However, if I increase SIZE to 100000 (100x) the program becomes slower. These are the observed results on the same machine:

  • 407.844µs
  • 432.607µs
  • 397.67µs
  • 465.959µs
  • 445.101µs

Why is the value of SIZE making such a big difference? The number of iterations will always be the same (1000)...

  • 写回答

1条回答 默认 最新

  • donglan8999 2018-06-03 19:31
    关注

    In one sentence

    Because you are also counting the time to allocate the slice

    Explanation

    In your code, you are creating the start variable just before your big slice a.

    func main() {
        start := time.Now()
        a := [SIZE]int {}
        //...
    }
    

    By doing this, you are ignoring the fact that allocating a slice with 1000 items is much faster than allocating a slice with 100000 items.

    You have to move this initialization after the allocation. The size of the slice should not affect the time to loop through it up to a certain number of (equal) iterations.

    In my benchmarks:

    | Items  | ns/op | Count slice allocation? |
    |--------|-------|-------------------------|
    | 1000   | 1411  | YES                     |
    | 100000 | 66565 | YES                     |
    | 1000   | 837   | NO                      |
    | 100000 | 855   | NO                      |
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度