关闭

一个简单的测试代码性能的方法

发表于:2010-9-17 13:22

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:saturnman(163blog)    来源:51Testing软件测试网采编

  代码运行的绝对时间和机器的许多因素有关,如下所列就是一些常见的因素。

  机器硬件配置和特性

  机器的系统种类

  机器的测试时同时运行的其它程序的繁忙程度

  机器软件包安装情况

  机器进程序调度情况

  代码编译优化情况和编译器种类

  我简单整理了一下,利用win32 api函数,QueryPerformanceCounter 来达到精确计时的目地。构造了一个测试代码性能的类,自已用了感觉还不错,想到别人也可能用到计算程序性能的问题,就发出来共享一下,如果有什么意见或是bug,可以联系我。

/*
 * KBestMeasure.h
 * A class to test code performance using k best method
 * Contributors:
 * Created by saturnman <saturnman AT 163.com>
 * THIS SOFTWARE IS NOT COPYRIGHTED
 *
 * This source code is offered for use in the public domain. You may
 * use, modify or distribute it freely.
 *
 * This code is distributed in the hope that it will be useful but
 * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
 * DISCLAIMED. This includes but is not limited to warranties of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#ifndef MEASURE_H_
#define MEASURE_H_
#include <iostream>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <iterator>
#include <algorithm>
#include <windows.h>
#include <functional>
#include <numeric>
using namespace std;
class Measure
{
    public:
        enum STATE{before_init_s,run_s,stop_s};
    public:
        Measure()
        {
            this->m_state = before_init_s;
        }
        void start()
        {
            QueryPerformanceCounter(&(this->m_start_tick));
            this->m_state = run_s;
        }
        void stop()
        {
            if(this->m_state != run_s)
            {
                cerr<<"Measure in wrong state."<<endl;
                exit(1);
            }
            QueryPerformanceCounter(&(this->m_end_tick));
            this->m_state = stop_s;
        }
        int get_result()
        {
            int result;
            if(this->m_state != stop_s)
            {
                cerr<<"Measure in wrong state."<<endl;
                exit(1);
            }
            else
            {
                result = m_end_tick.QuadPart-m_start_tick.QuadPart;
            }
            return result;
        }
    private:
        LARGE_INTEGER m_start_tick;
        LARGE_INTEGER m_end_tick;
        STATE m_state;
};

41/41234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号