1

So i have been using this function for codechef problems for quite some while now as a fast input method for integers.

My question is how this actually works,what is fgetc_unlocked(stdin) (even though its commented) and most importantly how can I optimise it to run for long and long long.

Here is the code:

inline void Scan_f(int a)
{
char c = 0;
while(c<33)//shouldn't value of c to compare be less than 9 as digit vary between 0 to 9?? 
//c = fgetc_unlocked(stdin);
c = getc(stdin);
a = 0;
while(c>33)
{
a = a*10 + c - '0';
//c = fgetc_unlocked(stdin);
c = getc(stdin);
}
4

1 回答 1

2

在我看来,代码应该是:

inline unsigned long long Scan_f()
{
    int c;
    do
        c = fgetc(stdin);
    while ( (c < '0' || c > '9') && c != EOF );

    unsigned long long a = 0;
    while ( c >= '0' && c <= '9' )
    {
        a = a*10 + (c - '0');
        c = fgetc(stdin);
    }
    return a;
}

在您发布的代码中,a是一个按值传递的参数,因此尚不清楚调用函数将如何发现您对a.

fgetc_unlocked函数应该是一个更快的版本fgetc。这是一个 GNU 扩展。

成为有符号类型没有意义a,因为您的解析永远无法检索到负值。

此版本不检查溢出;如果你想处理这种可能性,那么你需要在做之前添加一个检查a = a*10

不用担心c < '0'etc. 部分的效率,编译器已经为您生成了最佳代码。他们可以很好地处理这样的简单情况。当然,它可以比从输入流中读取字符的速度更快地检查它;输入流速度将成为瓶颈。

于 2014-04-07T05:43:06.700 回答