```go
package main
import (
"fmt"
"sync"
"runtime"
"os/exec"
"strconv"
)
var counter int =0
var thcounter int = 0
func pings(ips string,lock *sync.Mutex){
c :=exec.Command("ping",ips,"-c 1 -W 1")
err:=c.Run()
if err ==nil {
lock.Lock()
counter = counter+1
fmt.Printf("ip addr%s is ok\n",ips)
thcounter +=1
lock.Unlock()
}else{
lock.Lock()
thcounter +=1
lock.Unlock()
}
}
func main(){
runtime.GOMAXPROCS(8)
lock :=&sync.Mutex{}
for i:=1;i<254;i+=1{
ips :="202.102.201."+strconv.Itoa(i)
go pings(ips,lock)
}
for{
lock.Lock()
c :=thcounter
lock.Unlock()
runtime.Gosched()
if c>=253 {
fmt.Println(counter)
break
}
}
}
```
上面的代码执行起来 需要耗时 10秒多 详情如下:
real 0m10.705s
user 0m10.481s
sys 0m0.514s
而我写的python 只需要不到3秒钟就可以搞定了
希望大神帮我看看,为什么这个代码那么的慢
用了lock的原因吧。我改写了一下,稍微快点。
代码如下:
```go
func pings(ips string,ch chan bool) {
c := exec.Command("ping", ips, "-c 1 -W 1")
err := c.Run()
if err == nil {
fmt.Printf("ip addr%s is ok\n", ips)
ch <- true
} else {
ch <- false
}
}
func main() {
var counter int = 0
ch := make(chan bool, 8)
runtime.GOMAXPROCS(8)
for i := 1; i < 254; i += 1 {
ips := "202.102.201." + strconv.Itoa(i)
go pings(ips, ch)
}
for i := 1; i < 254; i += 1 {
if <-ch {
counter += 1
}
}
fmt.Println(counter)
close(ch)
}
```
#5
更多评论