草庐IT

performance - Golang goroutine 在添加并发时变慢

coder 2024-07-13 原文

我正在研究golang和goroutine的使用。
使用此示例代码,在我具有 4 个逻辑 CPU 的 PC 上,我无法理解为什么我没有任何性能提升。

如果我添加并发,那么它所花费的时间往往会比没有并发的原始时间慢。

2017/10/27 13:57:17 Starting 1 threads
2017/10/27 13:57:27 Id routine: 0  rate: 232.558140
2017/10/27 13:57:27 Current total rate was 232.56 K/s
2017/10/27 13:57:27 Starting 1 threads
2017/10/27 13:57:37 Id routine: 0  rate: 357.142857
2017/10/27 13:57:37 Current total rate was 357.14 K/s


2017/10/27 13:58:04 Starting 2 threads
2017/10/27 13:58:14 Id routine: 0  rate: 131.578947
2017/10/27 13:58:14 Id routine: 1  rate: 129.870130
2017/10/27 13:58:14 Current total rate was 261.45 K/s
2017/10/27 13:58:14 Starting 2 threads
2017/10/27 13:58:24 Id routine: 1  rate: 144.927536
2017/10/27 13:58:24 Id routine: 0  rate: 151.515152
2017/10/27 13:58:24 Current total rate was 296.44 K/s

2017/10/27 13:59:15 Starting 3 threads
2017/10/27 13:59:25 Id routine: 2  rate: 94.339623
2017/10/27 13:59:25 Id routine: 0  rate: 92.592593
2017/10/27 13:59:25 Id routine: 1  rate: 90.090090
2017/10/27 13:59:25 Current total rate was 277.02 K/s
2017/10/27 13:59:25 Starting 3 threads
2017/10/27 13:59:35 Id routine: 2  rate: 92.592593
2017/10/27 13:59:35 Id routine: 0  rate: 90.090090
2017/10/27 13:59:35 Id routine: 1  rate: 101.010101
2017/10/27 13:59:35 Current total rate was 283.69 K/s

2017/10/27 14:00:12 Starting 4 threads
2017/10/27 14:00:22 Id routine: 1  rate: 56.818182
2017/10/27 14:00:22 Id routine: 3  rate: 56.818182
2017/10/27 14:00:22 Id routine: 0  rate: 61.349693
2017/10/27 14:00:22 Id routine: 2  rate: 62.500000
2017/10/27 14:00:22 Current total rate was 237.49 K/s
2017/10/27 14:00:22 Starting 4 threads
2017/10/27 14:00:32 Id routine: 1  rate: 67.114094
2017/10/27 14:00:32 Id routine: 3  rate: 61.349693
2017/10/27 14:00:32 Id routine: 0  rate: 57.803468
2017/10/27 14:00:32 Id routine: 2  rate: 65.789474
2017/10/27 14:00:32 Current total rate was 252.06 K/s

并且,这是带有 goroutine 的并发代码:

package main

import (
    "fmt"
    "log"
    "sync"
    "time"
)

var (
    tryArr           []string
    goroutineQuit    = make(chan struct{})
    concurrencyMapHQ = struct {
        sync.RWMutex
        HQ map[int]float64
    }{HQ: make(map[int]float64)}
)

func rateStats() {
    var totalRate float64
    for i, rate := range concurrencyMapHQ.HQ {
        log.Printf("Id routine: %d  rate: %f", i, rate)
        totalRate += rate
    }

    log.Printf("Current total rate was %.2f K/s", totalRate)
}

func stopThreads(threads int) {
    for i := 0; i < threads; i++ {
        goroutineQuit <- struct{}{}
    }

    rateStats()
}

func runThreads(threads int, steps int) {
    log.Printf("Starting %d threads", threads)

    for i := 0; i < threads; i++ {
        i := i
        go func(id int, steps int) {
            calculate(i, steps)
        }(i, steps)
    }
}

func calculate(idRoutine int, steps int) {
    var (
        possibles []string
        numBatchs = 0
        t1        = time.Now()
    )

    for {
        select {
        case <-goroutineQuit:
            return
        default:
            possibles = nil

            for _, nonce := range tryArr {
                possibles = append(possibles, nonce)
            }

            numBatchs++
            if numBatchs == 99 {
                t2 := time.Now()

                timeExecution := t2.Sub(t1) / time.Millisecond

                concurrencyMapHQ.Lock()
                concurrencyMapHQ.HQ[idRoutine] = float64(steps) / float64(timeExecution)
                concurrencyMapHQ.Unlock()

                numBatchs = 0
                t1 = t2

            }
        }
    }
}

func main() {
    threads := 4
    steps := 10000

    tryArr = make([]string, steps)
    for i := 0; i < steps; i++ {
        tryArr[i] = fmt.Sprintf("indice: %d", i)
    }

    for {
        runThreads(threads, steps)
        time.Sleep(10 * time.Second)
        stopThreads(threads)

        runThreads(threads, steps)
        time.Sleep(10 * time.Second)
        stopThreads(threads)
    }
}

最佳答案

possibles 案例分配 default:

default:
    //possibles = nil
    possibles = make([]string, 0, len(tryArr))

例如possibles = nil

2017/10/27 10:59:35 GOMAXPROCS: 4
2017/10/27 10:59:35 Starting 4 threads
2017/10/27 10:59:45 Id routine: 3  rate: 20.576132
2017/10/27 10:59:45 Id routine: 2  rate: 21.276596
2017/10/27 10:59:45 Id routine: 0  rate: 19.960080
2017/10/27 10:59:45 Id routine: 1  rate: 21.276596
2017/10/27 10:59:45 Current total rate was 83.09 K/s
2017/10/27 10:59:45 Starting 4 threads
2017/10/27 10:59:55 Id routine: 2  rate: 20.533881
2017/10/27 10:59:55 Id routine: 0  rate: 20.576132
2017/10/27 10:59:55 Id routine: 1  rate: 19.801980
2017/10/27 10:59:55 Id routine: 3  rate: 20.746888
2017/10/27 10:59:55 Current total rate was 81.66 K/s
57.08user 2.16system 0:20.02elapsed 295%CPU

还有,possibles = make([]string, 0, len(tryArr))

2017/10/27 10:57:33 GOMAXPROCS: 4
2017/10/27 10:57:33 Starting 4 threads
2017/10/27 10:57:43 Id routine: 0  rate: 112.359551
2017/10/27 10:57:43 Id routine: 1  rate: 104.166667
2017/10/27 10:57:43 Id routine: 2  rate: 91.743119
2017/10/27 10:57:43 Id routine: 3  rate: 112.359551
2017/10/27 10:57:43 Current total rate was 420.63 K/s
2017/10/27 10:57:43 Starting 4 threads
2017/10/27 10:57:53 Id routine: 0  rate: 123.456790
2017/10/27 10:57:53 Id routine: 1  rate: 126.582278
2017/10/27 10:57:53 Id routine: 2  rate: 113.636364
2017/10/27 10:57:53 Id routine: 3  rate: 119.047619
2017/10/27 10:57:53 Current total rate was 482.72 K/s
58.11user 2.32system 0:20.01elapsed 302%CPU

你的结果是什么?


随着“threads”[1,2,3,4]和possibles = make([]string, 0, len(tryArr))的增加,

$ cat /proc/cpuinfo | grep 'cpu cores' | uniq
cpu cores   : 4

.

2017/10/27 11:19:03 GOMAXPROCS: 4
2017/10/27 11:19:03 Starting 1 threads
2017/10/27 11:19:13 Id routine: 0  rate: 285.714286
2017/10/27 11:19:13 Current total rate was 285.71 K/s
2017/10/27 11:19:13 Starting 1 threads
2017/10/27 11:19:23 Id routine: 0  rate: 312.500000
2017/10/27 11:19:23 Current total rate was 312.50 K/s
24.66user 1.13system 0:20.01elapsed 128%CPU

.

2017/10/27 11:19:28 GOMAXPROCS: 4
2017/10/27 11:19:28 Starting 2 threads
2017/10/27 11:19:38 Id routine: 0  rate: 238.095238
2017/10/27 11:19:38 Id routine: 1  rate: 217.391304
2017/10/27 11:19:38 Current total rate was 455.49 K/s
2017/10/27 11:19:38 Starting 2 threads
2017/10/27 11:19:48 Id routine: 1  rate: 192.307692
2017/10/27 11:19:48 Id routine: 0  rate: 217.391304
2017/10/27 11:19:48 Current total rate was 409.70 K/s
46.14user 2.07system 0:20.00elapsed 240%CPU

.

2017/10/27 11:19:53 GOMAXPROCS: 4
2017/10/27 11:19:53 Starting 3 threads
2017/10/27 11:20:03 Id routine: 2  rate: 142.857143
2017/10/27 11:20:03 Id routine: 1  rate: 149.253731
2017/10/27 11:20:03 Id routine: 0  rate: 147.058824
2017/10/27 11:20:03 Current total rate was 439.17 K/s
2017/10/27 11:20:03 Starting 3 threads
2017/10/27 11:20:13 Id routine: 2  rate: 153.846154
2017/10/27 11:20:13 Id routine: 1  rate: 156.250000
2017/10/27 11:20:13 Id routine: 0  rate: 153.846154
2017/10/27 11:20:13 Current total rate was 463.94 K/s
52.41user 2.21system 0:20.01elapsed 273%CPU

.

2017/10/27 11:20:25 GOMAXPROCS: 4
2017/10/27 11:20:25 Starting 4 threads
2017/10/27 11:20:35 Id routine: 1  rate: 106.382979
2017/10/27 11:20:35 Id routine: 2  rate: 102.040816
2017/10/27 11:20:35 Id routine: 0  rate: 125.000000
2017/10/27 11:20:35 Id routine: 3  rate: 117.647059
2017/10/27 11:20:35 Current total rate was 451.07 K/s
2017/10/27 11:20:35 Starting 4 threads
2017/10/27 11:20:45 Id routine: 1  rate: 111.111111
2017/10/27 11:20:45 Id routine: 2  rate: 112.359551
2017/10/27 11:20:45 Id routine: 0  rate: 119.047619
2017/10/27 11:20:45 Id routine: 3  rate: 128.205128
2017/10/27 11:20:45 Current total rate was 470.72 K/s
58.80user 2.20system 0:20.01elapsed 304%CPU

总而言之,您似乎在对 Go 垃圾收集器进行基准测试。垃圾收集不是免费的。尽量减少分配。使用 Go testing package 基准工具。

关于performance - Golang goroutine 在添加并发时变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46974890/

有关performance - Golang goroutine 在添加并发时变慢的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  5. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  6. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  7. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  8. ruby-on-rails - 在 Ruby on Rails 中添加 boolean 列值 - 2

    我正在开发一个创建网络博客的RubyonRails项目。我希望将一个名为featured的boolean数据库字段添加到Post模型中。该字段应该可以通过我添加的事件管理界面进行编辑。我使用了以下代码,但我什至没有在网站上显示另一列。$railsgeneratemigrationaddFeaturedfeatured:boolean$rakedb:migrate我是RubyonRails的新手,非常感谢任何帮助。我的index.html.erb文件中的相关代码(views):FeaturedPost架构.rb:ActiveRecord::Schema.define(:version=>

  9. ruby - 如何将便捷类方法添加到 ruby​​ 中的 Singleton 类 - 2

    假设我有一个这样的单例类:classSettingsincludeSingletondeftimeout#lazy-loadtimeoutfromconfigfile,orwhateverendend现在,如果我想知道使用什么超时,我需要编写如下内容:Settings.instance.timeout但我宁愿将其缩短为Settings.timeout使这项工作有效的一个明显方法是将设置的实现修改为:classSettingsincludeSingletondefself.timeoutinstance.timeoutenddeftimeout#lazy-loadtimeoutfromc

  10. ruby-on-rails - 向 Rails 3 添加 Ruby 扩展方法的最佳实践? - 2

    我有一个要在我的Rails3项目中使用的数组扩展方法。它应该住在哪里?我有一个应用程序/类,我最初把它放在(array_extensions.rb)中,在我的config/application.rb中我加载路径:config.autoload_paths+=%W(#{Rails.root}/应用程序/类)。但是,当我转到railsconsole时,未加载扩展。是否有一个预定义的位置可以放置我的Rails3扩展方法?或者,一种预先定义的方式来添加它们?我知道Rails有自己的数组扩展方法。我应该将我的添加到active_support/core_ext/array/conversion

随机推荐