我正在尝试对 PI (3.14159) 飞镖的蒙特卡洛计算进行基准测试。我已经用 Java、Groovy、BeanShell、Julia、Jython 和 Python(Python2 用 C 实现)实现了我的代码。
这是我的原始 Java 代码“MonteCarloPI.java”:
import java.util.Random;
public class MonteCarloPI {
public static void main(String[] args)
{
int nThrows = 0;
int nSuccess = 0;
double x, y;
long then = System.nanoTime();
int events=(int)1e8;
Random r = new Random();
for (int i = 0; i < events; i++) {
x = r.nextFloat(); // Throw a dart
y = r.nextFloat();
nThrows++;
if ( x*x + y*y <= 1 ) nSuccess++;
}
double itime = ((System.nanoTime() - then)/1e9);
System.out.println("Time for calculations (sec): " + itime+"\n");
System.out.println("Pi = " + 4*(double)nSuccess/(double)nThrows +"\n");
}
}
这是文件“MonteCarloPI.groovy”中的 Groovy 代码:
import java.util.Random
int nThrows = 0
int nSuccess = 0
double x, y
long then = System.nanoTime()
int events=1e8
r = new Random()
for (int i = 0; i < events; i++) {
x = r.nextFloat() // Throw a dart
y = r.nextFloat()
nThrows++
if ( x*x + y*y <= 1 ) nSuccess++
}
itime = ((System.nanoTime() - then)/1e9)
System.out.println("Time for calculations (sec): " + itime+"\n")
System.out.println("Pi = " + 4*(double)nSuccess/(double)nThrows +"\n")
或者,我删除了诸如“float”和“int”(即松散类型)之类的定义。这使用“松散”类型检查性能。
我已将“MonteCarloPI.groovy”重命名为 BeanShell 脚本文件“MonteCarloPI.bsh”(BeanShell 的语法与 Groovy 非常相似)
对于标准 Python 语言,代码“MonteCarloPI_CPython.py”如下所示:
import random,time
nThrows,nSuccess = 0,0
then = time.time()
events=int(1e8)
for i in xrange(events):
x,y = random.random(),random.random(); # Throw a dart
nThrows +=1
if ( x*x + y*y <= 1 ): nSuccess+=1
itime = time.time() - then
print ("Time: ",itime,"sec Pi = ",4*nSuccess/float(nThrows))
此代码在 CPython 2.7.18(用 C 实现的 Python)或 Jython 2.7.2(Java 实现)中执行。对于 Python 3.8.3(“Python3”),将“xrange”替换为“range”。
千万里不及你
人到中年有点甜
慕斯709654
随时随地看视频慕课网APP
相关分类