Search code examples
c++generatoraveragetiming

Timing generator in c++


I completed a prime generating program. Now, i want to test for the amount of time it takes to all of the primes and store these numbers in an array. I wrote this code....

#include <iostream>
#include <ctime>
using namespace std;

int main ()
{


    int long MAX_NUM = 1000000;
    int long MAX_NUM_ARRAY = MAX_NUM+1;
    int long sieve_prime = 2;
    int long sieve_prime_constant = 0;
    int time_store = 0;
    int *Num_Array = new int[MAX_NUM_ARRAY];
    std::fill_n(Num_Array, MAX_NUM_ARRAY, 3);
    Num_Array [0] = 1;
    Num_Array [1] = 1;

while (time_store<=100)
{
    clock_t time1,time2;
    time1 = clock();
    while (sieve_prime_constant <= MAX_NUM_ARRAY)
    {
        if (Num_Array [sieve_prime_constant] == 1)  
        {

            sieve_prime_constant++;
        }
        else
        {
            Num_Array [sieve_prime_constant] = 0;  
            sieve_prime=sieve_prime_constant; 
             while (sieve_prime<=MAX_NUM_ARRAY - sieve_prime_constant)  
            {
                sieve_prime = sieve_prime + sieve_prime_constant;
                Num_Array [sieve_prime] = 1;
            }
            if (sieve_prime_constant <= MAX_NUM_ARRAY)
            {
                sieve_prime_constant++;
                sieve_prime = sieve_prime_constant;
            }
        }
    }
    time2 = clock();
    delete[] Num_Array;
    cout << "It took " << (float(time2 - time1)/(CLOCKS_PER_SEC)) << " seconds to    execute    this loop." << endl;
    cout << "This loop has already been executed " << time_store << " times." << endl;
    float Time_Array[100];
    Time_Array[time_store] = (float(time2 - time1)/(CLOCKS_PER_SEC));
    time_store++;
}


return 0;

}

When i run it, the program seems to go through the long loop once then crash. What is going wrong, and how can i fix it?


Solution

  • You delete you numArray at the end of the first loop, so you reference NULL when you go around again...

    Not sure what you intend to do with the delete[] statement... but whatever you intended to do - either do it somewhere else, or do something else, or re-initialize the array, or... you can no doubt figure it out from here.