`

Request Analysis

阅读更多
用法:

python bencher.py threadcount duration hitfile


TEST SUMMARY
============
21 REQUESTS in 3s (7.00/s)
7.00 CYCLES in 3s (2.33/s)
  http://www.tl50.com/ status_count: 200=9 (avg 1338ms/req)
  http://www.google.com.hk/ status_count: 200=6 (avg 671ms/req)
  http://www.baidu.com/ status_count: 200=6 (avg 156ms/req)

编写test.txt 内容如下

http://www.google.com.hk/
http://www.baidu.com/




import socket
import thread
import httplib
import time
import sys
import urlparse
import Queue
import os

def check_urls(urls):
    for u in urls:
        url_o = urlparse.urlparse(u)
        conn = httplib.HTTPConnection(url_o.hostname, url_o.port)
        try:
            conn.request("GET", "%s%s?%s" % (url_o.path, url_o.params, url_o.query))
        except socket.gaierror:
            error("the url '%s' contains an unknown hostname" % u)
        except socket.error:
            error("the url '%s' contains an host/port combo that did not respond" % u)

        resp = conn.getresponse()
       
        if resp.status != 200:
            error("the url '%s' did not return 200 is %s" % (u,resp.status))

from itertools import cycle
def test_thread(q, duration, urls):
    looper = cycle(urls)
    ind_bench = dict((u, []) for u in urls)
    start = time.time()
    count = 0
    while time.time() - start < duration:
        url = looper.next()
        url_o = urlparse.urlparse(url)
        m_s = time.time()
        conn = httplib.HTTPConnection(url_o.hostname, url_o.port)
        conn.request("GET", "%s%s?%s" % (url_o.path, url_o.params, url_o.query))
        resp = conn.getresponse()
        ind_bench[url].append((time.time() - m_s, resp.status))
        count += 1
    q.put((count, ind_bench))

def thread_details(num, amt, urls, duration, details):
    def out(s):
        if 'VERBOSE' in os.environ:
            print s
    out('- Thread #%d -' % num)
    cycles = amt / float(len(urls))
    out('  %d total requests (%.2f/s), %.1f cycles (%.1f/s)' % (amt, float(amt) / duration,
    cycles, cycles / duration))
    url_data = {}
    for url in urls:
        stats = details[url]
        status_acc = {}
        tot_time = 0
        for tm, status in stats:
            tot_time += tm
            try:
                status_acc[status] += 1
            except KeyError:
                status_acc[status] = 1
        avg_time = tot_time / float(len(stats))
        out('  %s status_count: %s (avg %dms/req)' % (
        url, ', '.join([('%s=%s' % (k, v)) for k, v in status_acc.iteritems()]),
        avg_time * 1000))
        url_data[url] = (avg_time, status_acc)
    return cycles, url_data

def run_test(count, duration, urls):
    check_urls(urls)
    rec_q = Queue.Queue()
    for x in xrange(count):
        thread.start_new_thread(test_thread, (rec_q, duration, urls))

    results = []
    for x in xrange(count):
        results.append(rec_q.get())

    tot = 0
    cycles = 0
    total_acc = dict((u, {}) for u in urls)
    times = dict((u, 0) for u in urls)
    for x, res in enumerate(results):
        amt, details = res
        cyc, url_data = thread_details(x + 1, amt, urls, duration, details)
        tot += amt
        cycles += cyc
        for url, (avg_time, status_acc) in url_data.iteritems():
            times[url] += avg_time
            for code, c_count in status_acc.iteritems():
                try:
                    total_acc[url]
 += c_count
                except KeyError:
                    total_acc[url]
 = c_count

    print "TEST SUMMARY"
    print "============"
    print "%s REQUESTS in %ss (%.2f/s)" % (tot, duration, tot / float(duration))
    print "%.2f CYCLES in %ss (%.2f/s)" % (cycles, duration, cycles / float(duration))
    for url in urls:
        print '  %s status_count: %s (avg %dms/req)' % (
        url, ', '.join([('%s=%s' % (k, v)) for k, v in total_acc[url].iteritems()]),
        (times[url] / float(count)) * 1000)

   
def error(msg):
    sys.stderr.write('error: %s\n' % msg)
    sys.stderr.write('usage: %s threadcount duration hitfile\n' % sys.argv[0])
    raise SystemExit, 1

def get_urls_from_file(fn):
    return [line.strip() for line in open(fn) if line.strip()]

def main_with_argv():
    args = sys.argv[1:]
    if len(args) != 3:
        error("exactly three arguments are required")
    count, duration, hitfile = args
    try:
        count = int(count)
    except ValueError:
        error("argument #1 (count) must be an int")
    try:
        duration = int(duration)
    except ValueError:
        error("argument #2 (duration) must be an int")
    try:
        urls = get_urls_from_file(hitfile)
    except IOError:
        error("could not retrieve URL list from file '%s'" % hitfile)
    run_test(count, duration, urls)

if __name__ == '__main__':
    main_with_argv()

分享到:
评论

相关推荐

    pull-request-analysis-sample

    "pull-request-analysis-sample"是一个示例项目,旨在帮助我们理解如何通过可视化来评估开发团队的生产力。在这个项目中,主要使用了TypeScript作为编程语言,这是一种静态类型的JavaScript超集,提供了更严格的类型...

    表單簽核系統說明.docx

    8.需求分析與定議(Request Analysis & Definition):该部分是指对人力招聘系統的需求分析和定义,即对系统的需求进行分析和定义,以确保系统能够满足HR团队的需求。 9.統一約定(Unified Definition):该部分是...

    DEV0002_通用單據批量打印功能.docx

    3. 需求分析與定議 (Request Analysis & Definition) 为了满足用戶需求,通用單據批量打印功能需要满足以下需求: * 系統中所涉及的程序類命名空間和類的引用與 eHR 系統源代碼結構匹配。 * 系統中所涉及按鈕用 ...

    請假申請取消功能規格說明書.docx

    4. **需求分析与定义(Request Analysis & Definition)** 分析中提到,"Cancel Leave Confirm"是主要功能页面,员工在此界面可以发起取消申请。页面设计应包含搜索功能,支持通过工号、姓名和取消申请单号进行查找。...

    SDBM0002_簽核流程管理.doc

    2. 需求分析與定議(Request Analysis& Definition):该功能可以讓系統管理員進行需求分析,並对流程進行定義和修改。 3. 自動產生OBR:该功能可以自动產生OBR,減少人工输入的错误和时间。 4. 自動帶出IPPD人資經...

    初级软件工程师必备日语

    - **需求分析**:リクエストアナリシス(Request Analysis) - **项目管理**:プロジェクトマネジメント(Project Management) ### 三、会议与讨论 在项目中,参加会议和讨论是常有的事。了解如何在这些场合用...

    英文原版-Qualitative Data Analysis Practical Strategies 1st Edition

    Lecturers/instructors only - request a free digital inspection copy here Written by an experienced researcher in the field of qualitative methods, this dynamic new book provides a definitive ...

    pandas 0.19.2 : powerful Python data analysis toolkit

    pandas 0.19.2 (有API,带书签,英文) pandas: powerful Python data analysis toolkit Release 0.19.2 Wes McKinney & PyData Development Team Dec 24, 2016

    Object-Oriented Analysis and Design 第六章

    Object Oriented Analysis and Design 10Builder - MotivationThe Builder pattern separates the construction of a complex object from its representation so that the same construction process can create ...

    IEEE 802.11—Saturation Throughput Analysis

    该标准定义了两种访问机制:基本访问方法(Basic Access Mechanism)和请求发送/清除发送(Request to Send/Clear to Send, RTS/CTS)方法。本文将介绍一种简单但精确的分析模型来计算这两种访问方案下的饱和吞吐量...

    VS2005插件——工具条:加注释、过滤Code Analysis的warning

    其次,"添加AR"可能指的是添加“Action Request”或者“Activity Record”,这是一种跟踪和记录代码修改或功能改进请求的方法。在大型项目中,对代码的每一次修改都需有据可查,以确保版本控制和问题追踪的有效性。...

    source_analysis

    3. **详细VA请求程序(Detailed VA Request Procedure)** 可能是指在源码分析中,详细的需求验证和批准流程。这通常包括需求文档的编写,需求的评审,以及与团队和利益相关者的沟通确认。 4. **AVA过程(AVA_...

    lengtai.zip_HARQ_data throughput_throughput_throughput analysis

    在无线通信领域,HARQ(Hybrid Automatic Repeat-reQuest)是一种重要的错误纠正技术,它结合了ARQ(Automatic Repeat-reQuest)的重传机制和前向纠错编码(FEC)的优势,以提高数据传输的可靠性。在"lengtai.zip_...

    Sentiment-Analysis-App

    sentiment = {'polarity': analysis.sentiment.polarity, 'subjectivity': analysis.sentiment.subjectivity} return jsonify(sentiment) if __name__ == '__main__': app.run(debug=True) ``` 3. **接收和...

    Python爬取电影数据-进行可视化分析利用request爬取电影数据保存在csv文本,1.zip

    标题中的“Python爬取电影数据-进行可视化分析利用request爬取电影数据保存在csv文本,1.zip”表明这个压缩包包含了一个使用Python编程语言进行网络爬虫的数据获取过程,目标是抓取电影相关的数据,并进行了可视化...

    Log Analysis_Subs_V20.docx

    1. RR/CCCH DL/Paging Request Type2 Length0026: 这个记录涉及到了寻呼请求,其中DL代表下行链路,Paging Request是网络向手机发送的信号,通知手机有数据或呼叫等待。Type2长度0026可能是特定寻呼组的信息。 2. ...

    Practical-Data-Analysis-Second-Edition:实用数据分析第二版,由packt发行

    #Practical Data Analysis-Second Edition这是Packt出版的的代码存储库。 它包含从头到尾完成本书所必需的所有支持项目文件。 ##说明和导航所有代码都组织在文件夹中。 每个文件夹均以数字开头,后跟应用程序名称。 ...

    Aria-charts-analysis

    另外,拉取请求(Pull Request)是开源项目中常见的协作方式。开发者可以通过这种方式向项目主提交代码修改建议,以修复错误或改进功能。在"Aria-charts-analysis"项目中,作者鼓励社区成员发现并修复如歌曲持续时间...

    50166_SRIO_Debugging_Packet_Analysis_Guide_ver1

    通过阅读“LogiCORE IP Serial RapidIO Gen2–Debugging and Packet Analysis Guide”,用户能够学习到如何基于提供的示例设计进行仿真,并通过Core Generator工具生成核心。同时,这份指南也适用于在硬件中使用...

    Apache-Log-Analysis:Apache 日志分析框架

    并以字典的格式分发,例如:{ 'remote': '123.125.71.36', 'datetime': datetime.datetime(2017, 4, 6, 18, 9, 25, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800))), 'request': {'method': 'GET', '...

Global site tag (gtag.js) - Google Analytics