查看运行时间函数--比较运行速度

本文通过C++代码演示了三种不同的内存初始化方法:使用memset、for循环赋值及std::fill,并比较了它们的执行效率。实验采用clock()函数和自定义Time类进行计时,结果显示在该环境下,memset最快,for循环次之,std::fill最慢。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <time.h>
#include <string.h>
#include <algorithm>
using namespace std;
class Time
{
public:
    void Start() //开始计时
    {
        start_time=clock();
    }
    int End() //结束计时,返回消耗的时间。以ms为单位
    {
        return clock()-start_time;
    }
private:
    clock_t start_time;
};
const int MAX = 10000000;
char a[MAX];
int main()
{
    int i;
    char to = '/0';
    cout<<"to="<<to<<endl;

    Time t;
    t.Start();
    clock();
    memset(a,to,sizeof(a));
    cout << t.End() << endl;
    t.Start();
    clock();
    for(i=0; i<MAX; i++)
        a[i] = to;
    for(i=0; i<MAX; i++)
        cout<<a[i]<<" ";
    cout << t.End() << endl;
    t.Start();
    clock();
    fill(a,a+MAX,to);
    cout << t.End();
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值