简体   繁体   English

C ++中的时序生成器

[英]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? 发生了什么问题,我该如何解决?

You delete you numArray at the end of the first loop, so you reference NULL when you go around again... 您在第一个循环结束时删除了numArray ,因此当您再次遍历时引用NULL。

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. 不确定要使用delete[]语句做什么...但是想要做什么-可以在其他地方执行,或者执行其他操作,或者重新初始化数组,或者...毫无疑问从这里出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM