繁体   English   中英

C代码性能比较,为什么其中之一要快得多

[英]C code performance comparison, why is one of them much faster

最近,我开始从在线法官那里解决问题: http : //coj.uci.cu/

我解决了一个关于计算两个数的最小幂的问题

(完整说明: http : //coj.uci.cu/24h/problem.xhtml?pid=1158

样品输入

2    // This means we want to perform the algorithm twice for the next input
4
192

样品输出

4
64

解决后,您可以将您的答案与其他答案进行比较,因此这是两个解决相同问题的不同代码(基本思想是不断除以2,直到模数不同于零,然后求出最小乘方,然后得出2 *最少找到答案)

我的解决方案

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a,result;
    int i = 0;
    int leastPow = 1;
    scanf("%d",&a);             // Read the number of conversions
    for(i = 0; i < a; i++){
        scanf("%d",&result);    // Read the number to calculate the least pow
        while(result!=0){       // While there is still divisions to make...       
            if(result%2!=0)    
                break;          // hence we break the loop, we are done...
            result = result/2;  // Otherwise we can keep on dividing
            leastPow *= 2;
        }
        printf("%d\n",leastPow);// Print the result
        leastPow = 1;          // Re initialize for next number
    }
    return 0;
}

顶级解决方案之一(由nilre撰写)

#include<stdio.h>

int main()
{
    long long pot,n;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%Ld",&n);
        pot = 1;
        while(n)
            if(n%2 == 0)
            {
                pot *= 2;
                n /= 2;
            }else break;
        printf("%Ld\n",pot);
    }
    return 0;
}

对我来说,代码看起来非常相似,但在线裁判给出了以下性能结果

我的解决方案

Time: 37 ms
Mem:  1 MB
Size: 1 KB

其他解决方案

Time: 0 ms
Mem:  270 bytes
Size: 348 bytes

我对什么能在性能上产生如此巨大的变化感到非常好奇

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM