c++performancedigit

Shouldn't isdigit() be faster in c++?


I am using isdigit() function in c++, but i found it's slow, so i implemented my own is_digit(), see my code below:

#include<iostream>
#include<cctype>
#include<ctime>
using namespace std;
static inline bool is_digit(char c)
{
    return c>='0'&&c<='9';
}
int main()
{
    char c='8';
    time_t t1=clock(),t2,t3;
    for(int i=0;i<1e9;i++)
        is_digit(c);
    t2=clock();
    for(int i=0;i<1e9;i++)
        isdigit(c);
    t3=clock();
    cout<<"is_digit:"<<(t2-t1)/CLOCKS_PER_SEC<<"\nisdigit:"<<(t3-t2)/CLOCKS_PER_SEC<<endl;

    return 0;
}

After running, is_digit() took only 1 second(1161ms), but isdigit() took 4 seconds(3674ms), I know that isdigit is implemented by bit operation, Shouldn't isdigit() be faster than is_digit()?


update1

I use MS VS2010 with default option, release version, how do i do to make isdigit() faster than is_digit() in VS?

update2

Thanks to all of you. When in release mode in VS, project will be optimized for speed default(-O2).

All in release mode.

VS2010: is_digit:1182(ms) isdigit:3724(ms)

VS2013: is_digit:0(ms) isdigit:3806(ms)

Codeblocks with g++(4.7.1) with -O3: is_digit:1275(ms) isdigit:1331(ms)

So here is the conclusion:

is_digit() is faster than isdigit() in VS but slower than isdigit() in g++.

And isdigit() in g++ is faster than isdigit() in VS.

So "VS sucks" in performance?


Solution

  • Have a look on this code (works with g++) with -O3

    #include<iostream>
    #include<cctype>
    #include<ctime>
    #include <time.h>
    #include <sys/time.h>
    using namespace std;
    static inline bool is_digit(char c)
    {
        return c>='0'&&c<='9';
    }
    int main()
    {
        char c='8';
        struct timeval tvSt, tvEn;
        time_t t1=clock(),t2,t3;
        gettimeofday(&tvSt, 0);
        for(int i=0;i<1e9;i++)
            is_digit(c);
        gettimeofday(&tvEn, 0);
        cout << "is_digit:" << (tvEn.tv_sec - tvSt.tv_sec)*1000000 + (tvEn.tv_usec - tvSt.tv_usec) << " us"<< endl;
        gettimeofday(&tvSt, 0);
        for(int i=0;i<1e9;i++)
            isdigit(c);
        gettimeofday(&tvEn, 0);
        cout << "isdigit:" << (tvEn.tv_sec - tvSt.tv_sec)*1000000 + (tvEn.tv_usec - tvSt.tv_usec) << " us"<< endl;
    
        return 0;
    }
    

    Results:

    is_digit:1610771 us
    isdigit:1055976 us
    

    So, C++ implementation beats yours.
    Normally, when you measure performance, it's not a good idea to do it with seconds. At lease consider microseconds level.

    I'm not sure about VS. Please find out microsecond level clock and measure.

    PS. Please refer https://msdn.microsoft.com/en-us/library/19z1t1wy.aspx for VS optimizations