Почему мое время выполнения не записывается в файл? - PullRequest
0 голосов
/ 22 февраля 2019

Я использую библиотеку Chrono для вычисления времени выполнения моей конкретной строки кода.Я могу рассчитать время выполнения, но когда я пытаюсь записать это в файл, я получаю различные ошибки.Я получаю следующие ошибки:

нет совпадения для оператора << </p>

невозможно преобразовать dif в тип const unsigned char *

Вот примермой код

    int main ()
{   

    ofstream plot;
    plot.open("graph.txt");

    srand((unsigned)time(0));    


        int n = 250;
        std::cout <<"The size of the array is:" << n << std::endl;
        std::cout <<"\n";

        plot << n;
        int *arr = new int (sizeof(int)*n);

        for (int i=0;i<n;i++)
        {

            int number = (rand()%1000+1);
            arr[i] = number;
        }
        std::cout << "The array provided is:" << std::endl;
        for (int i=0;i<n;i++)
        {
            std::cout << arr[i] << " ";

        }
        std::cout << "\n";
        std::cout<<"\n";

                auto start = chrono::steady_clock::now();
                Selectionsort (arr,n);
                auto end = chrono::steady_clock::now();
                auto diffe = end-start; 
                double  a = (double ) diff;
                plot << diff;
                std::cout << "The execution time for average case is:" <<
                std::cout << chrono::duration <double, milli> (diffe).count() << " ms" << std::endl;

plot << dif;причина, по которой я получаю ошибкуВ этом коде я делаю расчет времени выполнения для лучшего, худшего и среднего случая и перенос размера массива и данных в файл для построения графика.У меня нет опыта использования библиотеки Chrono до </p>

1 Ответ

0 голосов
/ 22 февраля 2019

Проблема с длительностью может быть решена с помощью duration_cast, а другая проблема - это строка int *arr = new int (sizeof(int)*n);, которая, как заметил molbdnilo, выделяет только один int со значением sizeof(int)*n.Вы также можете использовать лучший генератор случайных чисел.Предложения в коде:

#include <iostream>
#include <fstream>
#include <chrono>
#include <vector> // std::vector
#include <random> // std::random

int main ()
{
    std::random_device rd;
    std::mt19937 generator(rd()); // seed a prng
    // and create a distribution object:
    std::uniform_int_distribution<int> rnd_dist(1, 1000); // [1,1000]

    // you can open the file directly like this:
    std::ofstream plot("graph.txt");
    // and check if it was opened successfully:
    if(!plot) {
        std::clog << "couldn't open file\n";
        return 1;
    }

    // I'll use a std::random generator instead of this:
    // srand((unsigned)time(0));

    int n = 250;
    std::cout <<"The size of the array is:" << n << "\n\n";

    plot << n; // you probably want  << "\n";  here
    // You had:
    //   int *arr = new int (sizeof(int)*n);
    // It should have been:
    //   int *arr = new int[n];
    // but the below is better since you don't have to delete[] it manually:
    std::vector<int> arr(n);

    for (int i=0; i<n; ++i) {
        arr[i] = rnd_dist(generator);
    }

    std::cout << "The array provided is:\n";
    for (int i=0; i<n; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n\n";

    // Edit: changed to high_resolution_clock
    auto start = std::chrono::high_resolution_clock::now();
    // the below call works, but consider changing the signaure of your Selectionsort() to:
    // void Selectionsort(std::vector<int>& arr);
    // The "n" is available via "arr.size();"
    Selectionsort(arr.data(), arr.size());
    auto end = std::chrono::high_resolution_clock::now();
    // diffe duration_cast fix:
    auto diffe = std::chrono::duration_cast<std::chrono::milliseconds>(end-start);
    plot << diffe.count(); // you probably want  << "\n";  here
    std::cout << "The execution time for average case is: " << diffe.count() << " ms\n";
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...