```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秒钟就可以搞定了
希望大神帮我看看,为什么这个代码那么的慢
把`Command("ping",ips,"-c 1 -W 1")` 换成`Command("ping", ips, "-c", "1", "-W", "1")`
每个选项是一个独立的参数.
代码修改了一下, **1秒多**就完成了.
```Go
package main
import (
"fmt"
"os/exec"
"runtime"
"strconv"
"sync"
"sync/atomic"
)
var counter int32 = 0
func pings(ips string, w *sync.WaitGroup) {
c := exec.Command("ping", ips, "-c", "1", "-W", "1")
err := c.Run()
if err == nil {
atomic.AddInt32(&counter, 1)
fmt.Printf("ip addr%s is ok\n", ips)
}
w.Done()
}
func main() {
runtime.GOMAXPROCS(4)
var w = &sync.WaitGroup{}
for i := 1; i < 254; i += 1 {
w.Add(1)
ips := "202.102.201." + strconv.Itoa(i)
go pings(ips, w)
}
w.Wait()
fmt.Println(counter)
}
```
Python代码没有格式化, 看不懂
#9
更多评论