测试技术培训:如何测试磁盘写的速度 2

5、程序实现如下(非常简单、不再解释):

// writeFileDemo.cpp : 定义控制台应用程序的入口点。

//

 

#include "stdafx.h"

#include <iostream>

#include <fstream>

using namespace std;

 

 

#include <windows.h>

#include <WinBase.h>

#include <ctime>

 

//目标写入文件

const char* g_psOutFile = "D:\\test_file\\1.txt";

 

//一次写入的Buffer大小

const long WRITE_BUFF_SIZE = 10*1024*1024;    //300MB字节

 

//写入次数

#define MAX_WRITE_CNT   5

 

 

//buffer每个字节初始化为'a'字符

void initBuf(char* pszBuf, int iCnt)

{

    for(int i = 0; i < iCnt; ++i)

    {

        pszBuf[i] = 97;

    }

}

 

//循环写入文件

void writeFileFun(char* szBuf)

{

    ofstream ofout(g_psOutFile);

    int i = 0;

 

    while(i < MAX_WRITE_CNT)

    {

        ofout << szBuf << endl;

        ++i;

    }

 

}

 

//测试写磁盘速度

void writeFileTestFun()

{

    //堆内存申请,显然栈内存不合适

    char* szTenMBBuf = (char*)malloc(WRITE_BUFF_SIZE); 

    (void)initBuf(szTenMBBuf, WRITE_BUFF_SIZE);

 

    size_t nBeginTicks = GetTickCount();

    cout << "BeginTime = " << nBeginTicks << endl;

 

    (void)writeFileFun(szTenMBBuf);

 

    size_t nEndTicks = GetTickCount();

    cout << "EndTime = " << nEndTicks << endl;

 

    size_t nSpan = nEndTicks - nBeginTicks;

    cout << "nSpanTime = " << nSpan << "ms" << endl; //ms

 

    float nTotalBytes = WRITE_BUFF_SIZE*MAX_WRITE_CNT;  //总写入字节数

    float nTotalTimes = (float)(nSpan) / 1000.0f;       //总耗费时间,单位s

 

    cout << "nTotalWriteBytes = " << nTotalBytes << endl;

    cout << "nTotalTimes = " << nTotalTimes << endl;

 

    float fSpeed =  nTotalBytes / nTotalTimes;

 

    cout << "Speed = " << fSpeed << "Byte/s" << endl;   //写入速度 Byte/s

    cout << "Speed = " << fSpeed / 1024.0f / 1024.0f << "MB/s" << endl; //写入速度 MByte/s

 

    if (NULL != szTenMBBuf)

    {

        free(szTenMBBuf);

        szTenMBBuf = NULL;

    }

}

int _tmain(int argc, _TCHAR* argv[])

{

    (void)writeFileTestFun();

    return 0;

}

posted @ 2016-01-21 15:55  北京茑萝信息  阅读(155)  评论(0编辑  收藏  举报