我只是做一些测试,看看我是否可以在出于某些科学目的调用 Fortran 函数时运行 Go。我想比较在我的计算机的一个核心上运行的 Goroutine 与在所有 22 个核心上运行的 Goroutine 的功能。当我运行以下代码时,无论 GOMAXPROCS 设置为多少,我都可以看到 22 个处理器中的 20 个正在使用。当我将其设置为 1 时,我应该只运行 1 个处理器,对吧?因此它会慢得多。然后将其设置为 22 或 NumCPU() 会更快。此外,如果有人能帮助我理解为什么我有 22 个处理器时只使用 20 个处理器,那就太好了。
package main
// #cgo LDFLAGS: mylib.o -L/usr/local/Cellar/gcc/8.2.0/lib/gcc/8 -lgfortran
// double calc( double );
import "C"
import (
"fmt"
"runtime"
"sync"
"time"
)
func simulate(numberOfSteps int, returnValues chan C.double, wg *sync.WaitGroup) {
defer wg.Done()
iValue := C.double(0.0)
for i := 0; i < numberOfSteps; i++ {
iValue = C.double(i)
returnValues <- C.calc(iValue)
}
}
func test_cpu_count(numberOfProcessors int, numberOfSimulations int, numberOfSteps int) {
fmt.Println("\nNumber of cores:", numberOfProcessors)
runtime.GOMAXPROCS(numberOfProcessors) // set number of cores to 1 (not default for Go)
var wg sync.WaitGroup // For synchronizing goroutines
wg.Add(numberOfSimulations)
returnValues := make(chan C.double, numberOfSimulations*numberOfSteps)
concurrentStart := time.Now()
for index := 0; index < numberOfSimulations; index++ {
go simulate(numberOfSteps, returnValues, &wg)
}
wg.Wait()
fmt.Println("Runtime:", time.Now().Sub(concurrentStart))
}
func main() {
const numberOfSimulations int = 22
const numberOfSteps int = 800
//*****************************************************
// Concurrency and Parallelism
// First Concurrent on a single core
//*****************************************************
numThreads := 1
test_cpu_count(numThreads, numberOfSimulations, numberOfSteps)
//***********************************************************
// Now Parallel on all cores
//***********************************************************
numThreads = runtime.NumCPU()
test_cpu_count(numThreads, numberOfSimulations, numberOfSteps)
}
一个人每天认真地、真诚地念念珠,可以知道许多真理。 圣母玛利亚是我们的良善顾问女士,可以为生活中的任何困境提供建议!
http://www.medjugorje.org/rosary.htm
知识、智慧、忠告和理解是圣灵(她的神圣配偶)七件礼物中的四件。