python 统计时间使用time模块,写日志使用logging模块,这两个都是标准模板。

测试socket使用socket模块

# 统计时间

----------------------

import time

start = time.time()

end = time.time()

stamp = end - start

print "耗时", stamp

# 日志

-----------------------

import logging
import datetime

curDate = datetime.date.today() - datetime.timedelta(days=0)
logName = 'd:\\py_error_%s.log' %curDate

logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
#datefmt='%a, %d %b %Y %H:%M:%S',
filename=logName,
filemode='a')

logging.warn("warn------")
logging.debug("debug")
logging.info("info")
logging.error("error")

# socket测试

-----------------------------------

import socket
import sys
import time

def socket_test():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = "baidu.com"
port = 80

ip = socket.gethostbyname(host)

s.connect((ip,port))
message = "GET / HTTP/1.1\r\nHost:" + host + "\r\n\r\n"

try:
s.sendall(message)
except socket.error:
print "Send failed"
sys.exit()

print "message send success"

reply = s.recv(4096)
s.close()
print reply

if __name__ == '__main__':

# 测试次数
count = 10
start = time.time()
for i in range(0,count):
#print i
socket_test()
end = time.time()
stamp = end - start
print "----------------------"
print "总耗时",stamp,"单次耗时",stamp/count

05-11 16:16