0

问题标题是不言自明的。我有一个需要动态大小的数组的运行循环。但我确实知道该大小的最大值将是,所以如果需要,我可以将其最大化而不是动态调整大小。

这是我的代码,我知道就可移植性而言,clock_t 可能不是计时的最佳选择,但 clock_t 提供的准确性很差。

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>

#define TEST_SIZE 1000000

using namespace std;

int main(int argc, char *argv[])
{
    int* arrayPtr = NULL;
    int  array[TEST_SIZE];
    int  it = 0;

    clock_t begin, end;

    begin = clock();
    memset(array, 0, sizeof(int) * TEST_SIZE);
    end = clock();
    cout << "Time to memset: "<< end - begin << endl;

    begin = clock();
    fill(array, array + TEST_SIZE, 0);
    end = clock();
    cout << "Time to fill: "<< end - begin << endl;

    begin = clock();
    for ( it = 0 ; it < TEST_SIZE ; ++ it ) array[it] = 0;
    end = clock();
    cout << "Time to for: "<< end - begin << endl;
}

这是我的结果:

Time to memset: 1590
Time to fill: 2334
Time to for: 2371

既然我知道 new & delete 现在会将数组清零,有没有比这些更快的方法?

请帮我!

4

4 回答 4

3

基本上你是在比较苹果和橘子。

memset and the for-loop explicitly set the memory content to a particular value(in your example 0). While, the new merely allocates sufficient memory(atleast as requested) and delete merely marks the memory free for reuse. There is no change in the content at that memory. So new and delete do not initialize/de-initialize the actual memory content.
Technically, the content in that memory has an Indeterminate value. Quite literally, the values maybe anything and you cannot rely on them to be anything specific.They might be 0 but they are not guaranteed to be. In fact using these values will cause your program to have an Undefined Behavior.

A new call for an class does two things:

  • Allocates requested memory &
  • Calls constructor for the class to initialize the object.

But note that in your case the type is an int and there is no default initialization for int.

于 2013-03-30T14:12:35.333 回答
2

new只分配一个内存块,它不会初始化分配的内存。要初始化数组,您可以使用memset()或手动进行。

于 2013-03-30T14:12:26.013 回答
0

Good compiler will optimize all 4 approaches into 1 call of memset. Also, what's the difference between 3rd and 4th approach?

You can also do

int  array[TEST_SIZE] = {};

gain readability and save 1 line of code.

于 2013-03-30T14:13:42.747 回答
0

I would resort to memset in this case. fill is generic, but the platform can offer you some really nice tricks in its implementation of memset. This is possible, because the function is unambigous in what it does and dumb enough:

  • It could employ (S)DMA for actual memory modification, which could have faster interface to memories. Also, while it runs the task, the CPU could do something else
  • When it knows it has to sequentially write contiguous memory region, it could do something preventive about cache invalidation
  • The implementation in ARM-based embedded systems can benefit from burst mode; it is realized with special assembler instruction (STMFD, STMFA etc.) and in this mode 3 writes are equal two normal writes timewise
于 2013-03-30T14:35:32.600 回答