memset效率问题

char buff[10]

初始化一个字符数组,只需要buff[0] = '\0'即可,没有必要用memset,在使用该buff时,需要注意末尾加'\0',这样性能比较好。


#include <iostream>
#include "sys/time.h"

void use_memset()
{
    timeval timestart,timeend;
    gettimeofday(×tart, NULL);

    for( int i = 0; i < 512; i ++)
    {
        char* buff = new char[1024*1024];
        memset(buff,0,1024*1024);
        delete[] buff;
    }

    gettimeofday(&timeend, NULL);
    double linStart = 0,linEnd = 0;
    linStart = ((double)timestart.tv_sec * 1000000 + (double)timestart.tv_usec);    //unit S
    linEnd = ((double)timeend.tv_sec * 1000000 + (double)timeend.tv_usec);       //unit S
    double time = linEnd-linStart;
    printf("%f/n",time);
}

void use_setlast()
{
    timeval timestart,timeend;
    gettimeofday(×tart, NULL);

    for( int i = 0; i < 512; i ++)
    {
        char* buff = new char[1024*1024];
        buff[1024*1024-1] = '/0';
        delete[] buff;
    }

    gettimeofday(&timeend, NULL);
    double linStart = 0,linEnd = 0;
    linStart = ((double)timestart.tv_sec * 1000000 + (double)timestart.tv_usec);    //unit S
    linEnd = ((double)timeend.tv_sec * 1000000 + (double)timeend.tv_usec);       //unit S
    double time = linEnd-linStart;
    printf("%f/n",time);
}

int main(int argc, char** argv)
{
    use_memset();
    use_setlast();
}


运行结果:
502575.000000
5342.000000
相差100倍。因此,能确定长度或者大概长度的情况下,请不要memset所有字符。

你可能感兴趣的:(null,delete,include,iostream)