力卉编程 | 算法:printf 耗时还是cout耗时?

2020-02-19  本文已影响0人  力卉编程

问题:printf 耗时还是cout耗时?
平常我们printf 和cout都可以打印调试信息,但是两个的效率是不一样的,你知道吗?
上代码:

#include <sys/timeb.h>
#include <iostream>
void log_msTime(const char *psStr)
{
    struct  tm      *ptm;
    struct  timeb   stTimeb;
    static  char    szTime[19] = {0};

    ftime(&stTimeb);
    ptm = localtime(&stTimeb.time);
    sprintf(szTime, "%02d:%02d:%02d.%03d",
            ptm->tm_hour, ptm->tm_min, ptm->tm_sec, stTimeb.millitm);
    szTime[18] = 0;
    //cout << "[" << psStr ;
    //cout << "]: " << szTime << endl;
    printf("%s/%s\n", psStr, szTime);
    //cerr << "[" << psStr ;
    //cerr << "]: " << szTime << endl;
}

调试代码

    log_msTime("printf_beg");
    printf("printf test\r\n");
    log_msTime("printf_end");

    log_msTime("cout_beg");
    std::cout<<("cout test\r\n");
    log_msTime("cout_end");

结果:

printf_beg/09:28:44.502
printf test
printf_end/09:28:44.503
cout_beg/09:28:44.503
cout test
cout_end/09:28:44.504

如果时间太短,可以考虑循环1000次、10000次试试。

    log_msTime("printf_beg");
    for(int i =0 ; i < 1000; i++)
        printf("printf test\r\n");
    log_msTime("printf_end");

    log_msTime("cout_beg");
    for(int i =0 ; i < 1000; i++)
        std::cout<<"cout  test\r\n";
    log_msTime("cout_end");

1000的结果:

printf_beg/09:34:59.892
printf_end/09:34:59.893
cout_beg/09:34:59.893
cout_end/09:34:59.893

本文仅提供问题的解决思路,明白了什么东西都好测试了!

文 | 力卉编程

上一篇 下一篇

猜你喜欢

热点阅读