You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
/*
|
|
Landesamt für Geoinformation und Landentwicklung, Referat 35
|
|
Einführung in die Sprache Go, 25.7.2017
|
|
Lektion 10: Unittests, Benchmarks und Profiling
|
|
*/
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"runtime"
|
|
"strconv"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
maxThreads, maxRoutines int8
|
|
|
|
gesuchteZahl int = 8978793242417717171 //5769977777
|
|
timestamp [2]int64
|
|
)
|
|
|
|
const ThreadFaktor int8 = 4 //!
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
func is_prime(n *int) bool {
|
|
if *n == 2 { // 2 ist die einzige gerade Primzahl
|
|
return true
|
|
} else if *n < 2 || *n&1 == 0 { // falls zahl < 2 oder gerade Zahl -> keine Primzahl (1 keine Primzahl)
|
|
return false
|
|
} else {
|
|
var reportChannel chan int = make(chan int, maxRoutines)
|
|
var stopChannel chan bool = make(chan bool, maxRoutines-1)
|
|
|
|
maxSchleife := int(math.Sqrt(float64(*n)))
|
|
|
|
for start := int8(3); start <= 3+(maxRoutines-1)*2; start += 2 {
|
|
wg.Add(1)
|
|
go func(s int8, e, g *int, mf *int8, cr chan int, cs chan bool) {
|
|
defer wg.Done()
|
|
select {
|
|
case <-cs: // Heh, Ihr könnt aufhören
|
|
return
|
|
default:
|
|
for i := int(s); i <= *e; i += int(*mf) * 2 {
|
|
//fmt.Println(i)
|
|
if *g%i == 0 {
|
|
select {
|
|
case cr <- i:
|
|
default:
|
|
fmt.Println("Channel voll!")
|
|
}
|
|
return
|
|
}
|
|
}
|
|
}
|
|
cr <- -1
|
|
}(start, &maxSchleife, n, &maxRoutines, reportChannel, stopChannel)
|
|
}
|
|
|
|
for j := int8(0); j < maxRoutines; j++ {
|
|
select {
|
|
case cvalue, cstatus := <-reportChannel:
|
|
if cstatus && cvalue > 0 {
|
|
fmt.Println("Teiler gefunden", cvalue)
|
|
for i := int8(1); i < maxRoutines; i++ { // 1 to < maxThreads ist effizienter als 0 to < maxThreads-1
|
|
stopChannel <- true
|
|
}
|
|
|
|
wg.Wait()
|
|
close(reportChannel)
|
|
close(stopChannel)
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
maxThreads = int8(runtime.NumCPU()) //!
|
|
maxRoutines = maxThreads * ThreadFaktor
|
|
runtime.GOMAXPROCS(int(maxThreads))
|
|
|
|
timestamp[0] = time.Now().UnixNano()
|
|
|
|
if is_prime(&gesuchteZahl) == true {
|
|
fmt.Println(strconv.Itoa(gesuchteZahl) + " IST eine Primzahl")
|
|
} else {
|
|
fmt.Println(strconv.Itoa(gesuchteZahl) + " ist KEINE Primzahl")
|
|
}
|
|
|
|
timestamp[1] = time.Now().UnixNano()
|
|
|
|
fmt.Printf("\nProzess ist fertig und hat mit %v Routinen, verteilt auf %v Threads, %v Sekunden gedauert!\n\n", maxRoutines, maxThreads, (float64(timestamp[1]-timestamp[0]) * math.Pow(10, -9)))
|
|
}
|