```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秒钟就可以搞定了
希望大神帮我看看,为什么这个代码那么的慢
```
#!/usr/bin/env python
#coding:utf-8
import os
import time
import threading
numlock =threading.RLock()
prlock=threading.RLock()
zxs=0
class pings(threading.Thread):
def __init__(self,num,interval):
threading.Thread.__init__(self)
self.nums=num
self.inter=interval
self.thread_stop=False
self.ns=0
def run(self):
global zxs
start=self.nums
while start<254 and not self.thread_stop:
ret=os.system('ping -c 1 -W 2 172.16.100.%d >/dev/null' % start)
if not ret:
prlock.acquire()
print 'ping 172.16.100.%d ok' % start
prlock.release()
self.ns +=1
start+=self.inter
#print '线程%d结束, 此线程共获得 %d 个在线数据' %(self.nums,self.ns)
numlock.acquire()
zxs+=self.ns
numlock.release()
def stop(self):
self.thread_stop=True
def pingt():
s=254
r=s-1
threads=[]
for i in range(1,s):
t=pings(i,r)
threads.append(t)
for i in threads:
i.start()
for i in threads:
i.join()
global zxs
print zxs,'个ip在线'
if __name__=='__main__':
pingt()
```
#7
更多评论