随机生成算法测试用例和性能测试
1、生成大量随机数2、传入函数指针,对不同的排序算法进行统一的性能测试//main.cpp#include <iostream>
#include <string>
#include "SortTestHelper.h"
template<typename T>
void SelectSort(T arr[], int n)
{
//寻找[i,n)区间内的最小值
for (int i = 0; i < n; i++)
{
int index = i;
for (int j = i + 1; j < n; j++)
{
if (arr < arr)
index = j;
}
if (index != i)
std::swap(arr, arr);
}
}
int main()
{
int n = 100000;
int* arr1 = SortTestHelper::GenerateRandomArray(n, 1, n);
SortTestHelper::TestSort("SelectSort", SelectSort, arr1, n);
SortTestHelper::PrintArr(arr1, n);
system("pause");
delete[] arr1;
return 0;
}
3、简单计时进行性能测试//SortTestHelper.h
#ifndef __SORTTESTHELPER_H
#define __SORTTESTHELPER_H
#include <cstdlib>
#include <ctime>
#include <time.h>
#include <cassert>
#include <iomanip>
namespace SortTestHelper {
int* GenerateRandomArray(int n, int rangeL, int rangeR)
{
assert(rangeL <= rangeR);
//生成有n个元素的随机数组,每个元素的取值范围为
int* arr = new int;
srand((unsigned int)time(NULL));
for (int i = 0; i < n; i++)
{
arr = rand() % (rangeR - rangeL + 1) + rangeL;
}
return arr;
}
template<typename T>
void PrintArr(T arr[], int n)
{
for (int i = 0; i < n; i++)
{
std::cout << arr << " ";
}
std::cout << std::endl;
}
template<typename T>
void TestSort(std::string sortName, void(*sort)(T [], int), T arr[], int n)
{
clock_t start = clock();
sort(arr,n);
clock_t end = clock();
assert(IsSorted(arr, n));
double time = double(end - start) / CLOCKS_PER_SEC;
std::cout << sortName << ": " << std::setprecision(6) << time << "s" << std::endl;
}
template<typename T>
bool IsSorted(T arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
if (arr > arr)
return false;
}
return true;
}
}
#endif
页:
[1]