簡體   English   中英

std :: chrono :: duration_cast count()返回零

[英]std::chrono::duration_cast count() returns zero

這是簡單的程序(數組排序):

#include <stdio.h>
#include <conio.h>
#include <array>
#include <algorithm>
#include <chrono>

typedef unsigned int myInt;

static void shellSort(myInt arr[], const myInt length) {
    if (length < 2) {
        return;
    }
    myInt i, j, step;
    myInt tmp;
    for (step = length / 2; step > 0; step /= 2) {
        for (i = step; i < length; i++) {
            tmp = arr[i];
            for (j = i; j >= step; j -= step) {
                if (tmp < arr[j - step]) {
                    arr[j] = arr[j - step];
                }
                else {
                    break;
                }
            }
            arr[j] = tmp;
        }
    }
}

void main() {
    const int arrSize = 2000;
    std::array<myInt, arrSize> arr;
    std::chrono::high_resolution_clock::time_point timeStart, timeEnd;

    //Array filling and shuffling
    for (int i = 0; i < arrSize; i++) {
        arr[i] = i + 1;
    }
    std::random_shuffle(arr.begin(), arr.end());

    //Array sorting and time measurement
    timeStart = std::chrono::high_resolution_clock::now();
    shellSort(arr._Elems, arrSize);
    timeEnd = std::chrono::high_resolution_clock::now();

    printf("%llu", std::chrono::duration_cast<std::chrono::nanoseconds>(timeEnd - timeStart).count());
    _getch();
}

並且返回0. 0納秒以對2000個元素進行排序。 看起來很奇怪。 我注意到它發生在函數執行時間很小但為0納秒的情況下-絕對是謊言。

屏幕截圖

Visual Studio 2013,版本-版本,平台x64,Win10 x64

請告訴我,為什么會發生這種情況?

C ++標准不需要std::high_resolution_clock的最低分辨率。

20.11.7.3

high_resolution_clock類[time.clock.hires] high_resolution_clock類的對象表示滴答周期最短的時鍾。 high_resolution_-clock可以是system_clock或stable_clock的同義詞。

重點: 可能是system_clock或stable_clock的同義詞

您需要檢查編譯器的文檔。 編譯器的std::high_resolution_clock的分辨率可能太粗糙,無法測量如此小的間隔,因此測量的開始和結束時間是相同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM