我正在使用合并排序对数组进行排序。我使用Chrono库测量时间,但有时结果为0。
int main() {
srand(50000);
int A[N];
for (int i = 0; i < N; i++) {
A[i] = rand();
}
cout << "Array non ordinato\n";
Stampa(A, N);
auto start = std::chrono::system_clock::now();
QuickSort(A, 0, N - 1);
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed = end - start;
cout << "\nArray ordinato\n";
Stampa(A, N);
cout << "Elapsed time in nanoseconds : "
<< chrono::duration_cast<chrono::nanoseconds>(end - start).count()
<< " ns" << endl;
cout << "Elapsed time in milliseconds : "
<< chrono::duration_cast<chrono::milliseconds>(end - start).count()
<< " ms" << endl;
cout << "Elapsed time: " << elapsed.count() << "s";
}
我用N
定义了#define N 300
。
[如果N
为300
,则经过时间(纳秒,毫秒或秒)为0
。如果增加N
,则经过时间大于零。我也需要时间来准备小阵列。我该如何解决?
如果要对较小的N排序提高精度,建议使用high resolution clock而不是系统时钟。
[像问题一样测量时间时,需要使用std::chrono::steady_clock
或is_steady
属性为true
的任何其他时钟。 std::chrono::system_clock
使用的挂钟可能会在任何给定时间改变。这是std::chrono::system_clock
的目的:代表系统的当前时间。
您可能还希望使用更多的元素来查看时间上任何有意义的差异。
尽管std::chrono::high_resolution
时钟本身就很诱人,但值得注意的是,从技术上讲,计时中没有高分辨率时钟。相反,它是具有最高可用分辨率的时钟的别名。引用标准:
class high_resolution_clock
的对象代表带有最短的滴答周期。high_resolution_clock
可能是的同义词system_clock
或steady_clock
。
当我们检查实现时,我们看到MSVC具有以下内容:
using high_resolution_clock = steady_clock;
而libstdc ++-v3具有:
/**
* @brief Highest-resolution clock
*
* This is the clock "with the shortest tick period." Alias to
* std::system_clock until higher-than-nanosecond definitions
* become feasible.
*/
using high_resolution_clock = system_clock;