samedi 19 mars 2022

Using element in vector as index in array?

I'm writing code that randomly generates a vector of indices, fetches a random one, then uses that index to fetch another index, and so on. However, my code seems to repeat a cycle of indices. Here is my full code:

vector<uint16_t>* genBuffer() {
    vector<uint16_t>* buffer = new vector<uint16_t>(256);
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> distr(0, 255);
    for (uint16_t i = 0; i < 256; i++) {
        (*buffer)[i] = distr(gen);
    }
    shuffle(buffer->begin(), buffer->end(), gen);
    return buffer;
}

double timeAccess(vector<uint16_t>* buff, uint64_t buffSize) {
    struct timespec start, stop;
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> distr(0, 255);
    auto index = distr(gen);
    auto nextIndex = (*buff)[index];
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (uint64_t i = 0; i <= buffSize; i++) {
        cout << nextIndex << endl;
        nextIndex = (*buff)[nextIndex];
    }    
    clock_gettime(CLOCK_MONOTONIC, &stop);
    double time_taken = (stop.tv_sec - start.tv_sec) - (double)(stop.tv_nsec - start.tv_nsec);
    double avgTime = time_taken/buffSize;
    return avgTime;
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        cout << "Please enter only one numerical argument." << endl;
        return -1;
    }
    uint64_t buffSize = atoi(argv[1]);
    auto randBuff = genBuffer();
    auto timeTaken = timeAccess(randBuff, buffSize);
    cout << "Average time per buffer read = " << timeTaken << " ns" << endl;
    return 0;
}

Here is an example run with an argument of 25:

35
218
157
9
4
214
225
246
123
92
195
114
200
33
138
13
17
35
218
157
9
4
214
225
246
123

As you can see, the pattern eventually repeats, although it shouldn't do that.

This code is part of a cache benchmark I was asked to write for class. Here is the full code for anyone willing to try:

https://github.com/aabagdi/CacheBenchmark

As well, I'm trying to time the average time per read in ns. Am I doing that correctly? Thanks!




Aucun commentaire:

Enregistrer un commentaire