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[j] < arr[index])
- index = j;
- }
- if (index != i)
- std::swap(arr[i], arr[index]);
- }
- }
-
- 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个元素的随机数组,每个元素的取值范围为[rangeL,rangeR]
- int* arr = new int[n];
- srand((unsigned int)time(NULL));
- for (int i = 0; i < n; i++)
- {
- arr[i] = 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[i] << " ";
- }
- 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[i] > arr[i + 1])
- return false;
- }
- return true;
- }
- }
-
- #endif
复制代码
|