我试图测量一些功能'运行时间(即Quicksort和Mergesort)。我想要进行多次测试,所以我使用" for"循环执行该功能并多次测量它的运行时间。问题是,在某些测试用例中,我会得到一些随机,不准确的运行时测量值。
以下是代码:
#include <iostream>
#include <chrono>
#include <random>
#include <vector>
auto seed = static_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch().count());
std::mt19937_64 rand_num(seed.count());
template <typename T, typename U>
void swap(T *a, U i, U j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
template <typename T>
void quicksort(T *a, unsigned long long left, unsigned long long right) {
unsigned long long i = left , j = right;
std::uniform_int_distribution<unsigned long long> range(0, (right - left) / 2);
T pivot = a[left + range(rand_num)];
while (left < j or i < right)
{
while (a[i] < pivot)
i++;
while (a[j] > pivot)
j--;
if (i <= j)
{
swap(a, i, j);
i++;
j--;
}
else
{
if (left < j)
quicksort(a, left, j);
if (i < right)
quicksort(a, i, right);
return;
}
}
}
int main() {
unsigned long long size, test, i;
long long x, y;
std::cout << "Test cases: ";
std::cin >> test;
std::cout << "Array size: ";
std::cin >> size;
std::vector<long long> a(size);
std::cout << "\nEnter the Minimum Size for the numbers: ";
std::cin >> x;
std::cout << "\nEnter the Maximum Size for the numbers: ";
std::cin >> y;
std::uniform_int_distribution<long long> range(x, y);
for (unsigned long long b = 1; b <= test; b++) {
for (i = 0; i <= size-1; i++)
a[i] = range(rand_num);
auto start = std::chrono::high_resolution_clock::now();
quicksort(a.data(), 0, size-1);
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::nanoseconds(end - start).count();
std::cout << "\nTest " << b << ": " << elapsed << " Nanoseconds";
}
std::cout << "\n\n";
system("pause");
return 0;
}
注意: