哪个是最快的数组清零? [英] Which is fastest for zeroing-out an array?

查看:185
本文介绍了哪个是最快的数组清零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The question title is quite self-explanatory. I have an run loop that need a dynamic-sized array. But I do know the maximum of that size is going to be, so if needed, I can max it out instead of dynamically-sizing it.

这里是我的代码,我知道clock_t可能不是在可移植性的时机的最佳选择,但clock_t提供不准确。

Here's my code, I know that clock_t probably not the best choice for timing in terms of portability, but clock_t provide bad accuracy.

#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

现在我知道新的&删除现在清零数组,有没有比这些更快?

Now that I know new & delete does now zero-out the array, is there any way faster than these?

请帮助我!

推荐答案

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

Basically you are comparing apples and oranges.

memset for-loop显式地将存储器内容设置为特定值(例如 0 中的)。而 new 只是分配足够的内存(至少根据请求)和 delete 内存可以自由重用。该内存中的内容没有变化。因此 new delete 不会初始化/取消初始化实际内存内容。

,则该内存中的内容具有
不确定值。字面上,值可能是任何东西,你不能依赖它们是任何具体的。它们可能是 0 但他们不能保证是。实际上,使用这些值会导致您的程序有 未定义的行为

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 调用一个类有两件事:

A new call for an class does two things:


  • 分配请求的内存&

  • 调用类的构造函数来初始化对象。

但是请注意,在你的情况下,类型是 int ,并且没有默认初始化 int

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

这篇关于哪个是最快的数组清零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆