使用python

时间:2016-09-14 09:03:49

标签: python curl

我正在尝试使用curl命令对我的Web服务器进行负载测试。

我能够运行多个curl命令,但现在我还想从所有执行的curl命令计算avg响应时间

from functools import partial
from multiprocessing.dummy import Pool
from subprocess import call

commands = []
command = "curl -s -w \"Time:%{time_total}\n\" -o /dev/null -k -X GET \"https://google.com\""
for i in range(10):   # run 10 curl commands in total
    commands.append(command)

pool = Pool(5) # Nummber of concurrent commands at a time
for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
    if returncode != 0:
       print("%d command failed: %d" % (i, returncode))

输出

Time:0.654
Time:0.689
Time:0.720
Time:0.725
Time:0.735
Time:0.624
Time:0.635
Time:0.633
Time:0.678
Time:0.708

如何捕获Time并计算平均响应时间?

由于

1 个答案:

答案 0 :(得分:1)

您可以创建由call执行的单独功能,而不是依赖于imap。然后,您可以使用允许您与子进程通信的Popen。下面的示例仅将时间写入stdout,然后将其捕获并返回到父进程:

from functools import partial
from multiprocessing.dummy import Pool
from subprocess import Popen, PIPE

def child(cmd):
    p = Popen(cmd, stdout=PIPE, shell=True)
    out, err = p.communicate()
    return out, p.returncode

commands = []
command = "curl -s -w \"%{time_total}\" -o /dev/null -k -X GET \"https://google.com\""
for i in range(10):   # run 10 curl commands in total
    commands.append(command)

pool = Pool(5) # Nummber of concurrent commands at a time

times = []
for i, (output, returncode) in enumerate(pool.imap(child, commands)):
    if returncode != 0:
       print("{} command failed: {}".format(i, returncode))
    else:
       print("{} success: {}".format(i, output))
       times.append(float(output))

print 'Average: {}'.format(sum(times) / len(times) if times else 0)

输出:

0 success: 0.109
1 success: 0.108
2 success: 0.103
3 success: 0.093
4 success: 0.085
5 success: 0.091
6 success: 0.109
7 success: 0.114
8 success: 0.092
9 success: 0.099
Average: 0.1003