/*

version :       1.0
Author  :       BryceQing
Time    :       4/14/21
Func    :       Σ with multi core
Go-ver  :       Go 1.16

*/
package main

import (
	"fmt"
	"math"
	"runtime"
	"sync"
	"time"
)

var mu sync.Mutex

func sum(begin, end int)  int64{
	var res int64= 0
	for i:=begin ; i < end; i++{
		res += int64(i)
	}
	return res
}

func sum_multicore(s, e int) int64{
	var wg sync.WaitGroup
	core_num := runtime.NumCPU()
	wg.Add(core_num)

	var sum_num int64 = 0
	len_t := e - s + 1
	div := len_t / core_num

	for i := 0 ; i < core_num; i++{
		tmp_s, tmp_e := i * div, (i + 1) * div
		if i == core_num - 1{
			tmp_e = e
		}
		go cal_tmp_sum(tmp_s, tmp_e, &wg, &sum_num)
	}

	wg.Wait()
	return sum_num
}

func cal_tmp_sum(s, e int, wg *sync.WaitGroup, sum_num *int64 )  {
	defer  wg.Done()
	var tmp_sum int64 = 0

	for i := s ; i < e; i++{
		tmp_sum += int64(i)
	}

	mu.Lock()
	*sum_num += tmp_sum
	mu.Unlock()
}

func main()  {

	arr_size := int(math.Pow10(10))

	t1 := time.Now()
	var res1 int64 = sum(0, arr_size)
	t2 := time.Now()

	t3 := time.Now()
	var res2 int64 = sum_multicore(0, arr_size)
	t4 := time.Now()

	fmt.Println("One cure is :", t2.Sub(t1), res1)
	fmt.Println("Multi core is :", t4.Sub(t3), res2)

}