c++ string 和 sprintf 性能测试

代码:

#ifdef _WIN32
#ifndef _WIN32_LEAN_AND_MEAN_
#define _WIN32_LEAN_AND_MEAN_
#endif
#include 
#include
#endif
#include 
#include 
#include 
using namespace std;

static inline uint64_t  turing_rdtsc()
{
#ifdef Linux
    union {
        uint64_t tsc_64;
        struct {
            unsigned int lo_32;
            unsigned int hi_32;
        };
    } tsc;

    asm volatile("rdtsc" :
    "=a" (tsc.lo_32),
        "=d" (tsc.hi_32));

    return tsc.tsc_64;
#else 
    LARGE_INTEGER tsc;
    //QueryPerformanceFrequency(&cpu_clock);
    QueryPerformanceCounter(&tsc);
    return tsc.QuadPart;
#endif
}


inline int time_to_str(char* str, int sTime, int mTime)
{
    char secbuf[7] = { 0 };
    char usecbuf[7] = "000000";
    sprintf(secbuf, "%06d", sTime);
    if (mTime)
        sprintf(usecbuf, "%06d", mTime);
    sprintf(str, "%c%c:%c%c:%c%c.%c%c%c", secbuf[0], secbuf[1],
        secbuf[2], secbuf[3],
        secbuf[4], secbuf[5],
        usecbuf[0], usecbuf[1], usecbuf[2]);
    return 0;
}

inline int time_to_str3(char* str, int sTime, int mTime)
{
    char secbuf[7] = { 0 };
    char usecbuf[7] = "000000";
    sprintf(secbuf, "%06d", sTime);
    if (mTime)
        sprintf(usecbuf, "%06d", mTime);
    sprintf(str, "%s:%s:%s.%3s", std::string(secbuf).substr(0, 2).c_str(),
        std::string(secbuf).substr(2, 2).c_str(),
        std::string(secbuf).substr(4, 2).c_str(),
        std::string(usecbuf).substr(0, 3).c_str());
    return 0;
}

inline int time_to_str2(char* str, int sTime, int mTime)
{
    str[0] = '0' + sTime / 100000;
    str[1] = '0' + sTime / 10000 % 10;
    str[2] = ':';
    str[3] = '0' + sTime / 1000 % 10;
    str[4] = '0' + sTime / 100%10;
    str[5] = ':';
    str[6] = '0' + sTime / 10 % 10;
    str[7] = '0' + sTime / 1 % 10;
    str[8] = '.';
    str[9] = '0' + mTime / 100000;
    str[10] = '0' + mTime / 10000 % 10;
    str[11] = '0' + mTime / 1000 % 10;
    return 0;
}

int main(void)
{
    int num = 100000;
    char buf[1024] = { 0 };
    long long ti = turing_rdtsc();
    for (int i = 0; i < num ; ++i)
    time_to_str(buf, 123, 456);
    cout << turing_rdtsc() - ti << endl;
    ti = turing_rdtsc();
    std::cout << buf << std::endl;

    for (int i = 0; i < num; ++i)
        time_to_str2(buf, 123, 456);
    cout << turing_rdtsc() - ti << endl;
    ti = turing_rdtsc();
    std::cout << buf << std::endl;

    for (int i = 0; i < num; ++i)
        time_to_str3(buf, 123, 456);
    cout << turing_rdtsc() - ti << endl;
    ti = turing_rdtsc();
    std::cout << buf << std::endl;

    return 0;
}


win下输出结果(window结果除以10应该就是微秒):

2072255
00:01:23.000
54146
00:01:23.000
9901978
00:01:23.000

linux 下输出结果(除2600就是微秒)(2600是我机器的频率):

251511278
00:01:23.000
12328883
00:01:23.000
517529737
00:01:23.000

你可能感兴趣的:(c++,数学建模,开发语言)