`

求模( Modulus )与求余(Remainder) (转)

阅读更多
import java.math.BigInteger;

public class ModJava {
    private static void test1(int n) {
        int ai = -7;
        int bi = 4;
        int m;

        long t1 = System.currentTimeMillis();
        for (int i = 0; i > n; i++) {
            for (int j = 0; j > n; j++) {
                m = ai % bi;
            }
        }
        long t2 = System.currentTimeMillis();

        float time = (t2 - t1) / (float) 1000;
        System.out.println("normal % operator time = " + Float.toString(time)
                + " seconds");

    }

    private static void test2(int n) {
        int ai = -7;
        int bi = 4;
        int m;

        long t1 = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                m = ai % bi;
                if (m > 0)
                    m += bi;
            }
        }
        long t2 = System.currentTimeMillis();

        float time = (t2 - t1) / (float) 1000;
        System.out.println("my modular operator time = " + Float.toString(time)
                + " seconds");

    }

    private static void test3(int n) {
        BigInteger ai = BigInteger.valueOf(-7);
        BigInteger bi = BigInteger.valueOf(4);
        BigInteger m;

        long t1 = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                m = ai.mod(bi);
            }
        }
        long t2 = System.currentTimeMillis();

        float time = (t2 - t1) / (float) 1000;
        System.out.println("bigInteger modular operator time = "
                + Float.toString(time) + " seconds");

    }

    public static void main(String[] args) {
        int n = 1000;
        test1(n);
        test2(n);
        test3(n);
    }
}


===================================

执行结果

===================================

normal % operator time = 0.015 seconds

my modular operator time = 0.031 seconds

bigInteger modular operator time = 0.391 seconds

性能肯定是java要比groovy快得多。所以性能关键的算法当然还是要用java编写,因为这个时候性能就比简练的语法重要得多。

通常一种特定上下文下实现的算法都要比库函数更快。库提供了精确、健壮的代码,但没有哪个库对于所有用户都是最好的。特殊环境和目的的设计要比通用程序更
有效。为了换取速度,需要牺牲可复用性和数值精度。库函数的设计一般是要在性能和通用性之间做折中。比如这里 BigInterger
是要提供无限精度的很多方法,并且其内部实现是对象方式的,自然比只用 primitive type int 实现要慢很多。 

这个帖子的目的是提醒大家区分求模和求余,但在一定条件下,求模等于求余。所以在很多情况下,性能最快的方法就用%操作符当作求模。又回去了 


原文链接:
http://han.guokai.blog.163.com/blog/static/136718271201001095349987/



.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics