Commit 8a40e931 authored by Boris Mühmer's avatar Boris Mühmer
Browse files

added variants with benchmark (but wron channel handling)

parent d0b36326
Loading
Loading
Loading
Loading
+54 −0
Original line number Diff line number Diff line
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path"
	"regexp"
	"runtime"
	"sync"
	"time"

	"repositories.muehmer.net/boris.muehmer/sotatool/offline"
)
@@ -34,6 +37,57 @@ func example01() {
	}

	// work on the file list
	tasks := []func(re *regexp.Regexp, files []os.FileInfo){processFiles001, processFiles002, processFiles003}
	results := make(chan string, len(tasks))
	for i, f := range tasks {
		start := time.Now()
		f(re, files)
		stop := time.Now()
		elapsed := stop.Sub(start)
		results <- fmt.Sprintf("f %d took %s", i, elapsed)
	}

	fmt.Println("Results:")
	for {
		fmt.Println(<-results)
	}
}

// Direct approach without any goroutines.
func processFiles001(re *regexp.Regexp, files []os.FileInfo) {
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		if re.MatchString(file.Name()) == false {
			continue
		}
		filename := file.Name()
		savegame.DumpJSONContents(path.Join(sourcedir, filename), destdir)
	}
}

// Use goroutines with a WaitGroup.
func processFiles002(re *regexp.Regexp, files []os.FileInfo) {
	var wg sync.WaitGroup
	for _, file := range files {
		if file.IsDir() {
			continue
		}
		if re.MatchString(file.Name()) == false {
			continue
		}
		wg.Add(1)
		go func(filename string) {
			defer wg.Done()
			savegame.DumpJSONContents(path.Join(sourcedir, filename), destdir)
		}(file.Name())
	}
	wg.Wait()
}

// Use goroutines, buffered channel, and a WaitGroup.
func processFiles003(re *regexp.Regexp, files []os.FileInfo) {
	numWorkers := runtime.NumCPU()
	filenames := make(chan string, numWorkers)
	var wg sync.WaitGroup