日期:2014-05-20 浏览次数:20639 次
import java.util.Random; import bsh.EvalError; import bsh.Interpreter; public class Test2 { public static void main(String[] args) throws EvalError { final int count = 5000; final int paramCount = 4; double[][] datas = new double[paramCount][count]; Random ran = new Random(); for(int i = 0; i < datas.length; i++) { for(int j = 0; j < datas[i].length; j++) { datas[i][j] = ran.nextDouble() * count; } } double[] results = new double[count]; long t0, t1; t0 = System.currentTimeMillis(); String exp = "$0 + $1 * $2 + $3"; eval(exp, results, datas); t1 = System.currentTimeMillis(); System.out.println(t1 - t0); // 测试正确性 double[] res = new double[count]; for(int j = 0; j < datas[0].length; j++) { for(int i = 0; i < datas.length; i++) { res[j] = datas[0][j] + datas[1][j] * datas[2][j] + datas[3][j]; } } for(int i = 0; i < count; i++) { if(results[i] != res[i]) { System.out.printf("error! %.6f --> %.6f%n", results[i], res[i]); } } } public static void eval(String expression, double[] results, double[]... datas) throws EvalError { String ep = expression.replaceAll("\\$(\\d+)", "datas[$1][j]"); String exp = " for(int j = 0; j < datas[0].length; j++) {" + " for(int i = 0; i < datas.length; i++) {" + " results[j] = " + ep + ";" + " } " + " }"; Interpreter bsh = new Interpreter(); bsh.set("datas", datas); bsh.set("results", results); bsh.eval(exp); results = (double[])bsh.get("results"); } }
------解决方案--------------------
xuexi
------解决方案--------------------
BeanShell 支持的是 Java 语言
------解决方案--------------------
哈哈,我终于知道前面为什么要 600ms 了,因为我多做了几次循环,哎,真粗心!