码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言排序一千万个随机数.开的双核.用了120秒,不知道怎么优化.

时间:2015-06-17 21:43:44      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:golang   go   go语言   

package main

import (
	"fmt"
	"os"
	"runtime"
	"test"
	"time"
)

var x chan []int = make(chan []int, 1)
var Num int = 10
var WNum int = 100

func main() {
	fmt.Println(time.Now())
	var list1, list2 []int
	var R chan []int = make(chan []int, 1)
	for i := 0; i < WNum; i++ {
		go Chan(Num, R)
	}
	for i := 0; i < WNum; i++ {
		select {
		case y := <-R:
			if len(list1) == 0 {
				list1 = y
			} else {
				list2 = y
				list1 = test.Merge(list1, list2)
			}
		}
	}
	fmt.Println(time.Now())
	fmt.Println(len(list1))
	File, _ := os.OpenFile("c.txt", os.O_RDWR|os.O_CREATE, 0777)
	File.Write([]byte(fmt.Sprint(list1)))
	File.Close()
}

func Chan(Num int, R chan []int) {
	var list1, list2 []int
	runtime.GOMAXPROCS(2)
	for i := 0; i < Num; i++ {
		go func() {
			x <- test.Rand_list(10000)
		}()
	}
	for i := 0; i < Num; i++ {
		select {
		case y := <-x:
			if len(list1) == 0 {
				list1 = y
			} else {
				list2 = y
				list1 = test.Merge(list1, list2)
			}
		}
	}
	R <- list1
}
目录:test下

package test

import (
	"math/rand"
)

func Rand_list(Num int) []int {
	var list []int
	for i := 0; i < Num; i++ {
		list = append(list, rand.Intn(100000))
	}
	for i := 0; i < Num; i++ {
		for j := i + 1; j < Num; j++ {
			if list[i] > list[j] {
				list[i], list[j] = list[j], list[i]
			}
		}
	}
	return list
}

package test

func Merge(list1, list2 []int) []int {
	list1_Num := len(list1)
	list2_Num := len(list2)
	var j int = 0
	var list3 []int
	for i, _ := range list1 {
	This:
		if list1[i] <= list2[j] {
			list3 = append(list3, list1[i])
			if i == list1_Num-1 {
				for z := j; z < list2_Num; z++ {
					list3 = append(list3, list2[z])
				}
				break
			}
		} else {
			if j <= list2_Num-1 {
				list3 = append(list3, list2[j])
				if j == list2_Num-1 {
					for j := i; j < list1_Num; j++ {
						list3 = append(list3, list1[j])
					}
					break
				}
				j++
				goto This
			}
		}
	}
	return list3
}



Go语言排序一千万个随机数.开的双核.用了120秒,不知道怎么优化.

标签:golang   go   go语言   

原文地址:http://blog.csdn.net/fyxichen/article/details/46536677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!