写出了python、java和cpp的代码跑了一下,发现一个很奇怪的问题:java的运行效率居然比cpp要高,看来得进一步去分析一下,为啥这样了。
python版本:
import random import time def calculate_pi(num_points): points_inside = 0 for _ in range(num_points): x = random.uniform(-1, 1) y = random.uniform(-1, 1) if (x**2 + y**2) <= 1: points_inside += 1 pi_approximation = 4 * points_inside / num_points return pi_approximation # 调用函数并输出结果 begin_time = time.perf_counter() result = calculate_pi(100000000) end_time = time.perf_counter() print("近似的圆周率值为:", result, "耗费的时间为: ",end_time-begin_time)
java版本
import java.util.Random; public class MonteCarloCalculatePi { public static void main(String[] args) { int numPoints = 100000000; long startTime = System.currentTimeMillis(); double result = calculatePi(numPoints); long endTime = System.currentTimeMillis(); System.out.println("近似的圆周率值为: " + result); System.out.println("计算耗时: " + (endTime - startTime)/1000 + " 秒"); } public static double calculatePi(int numPoints) { int pointsInside = 0; Random random = new Random(); for (int i = 0; i < numPoints; i++) { double x = random.nextDouble() * 2 - 1; double y = random.nextDouble() * 2 - 1; if (x * x + y * y <= 1) { pointsInside++; } } double piApproximation = 4.0 * pointsInside / numPoints; return piApproximation; } }
cpp版本
#include <iostream> #include <random> #include <chrono> double calculatePi(int numPoints) { int pointsInside = 0; std::random_device rd; std::default_random_engine generator(rd()); std::uniform_real_distribution<double> distribution(-1.0, 1.0); for (int i = 0; i < numPoints; i++) { double x = distribution(generator); double y = distribution(generator); if (x * x + y * y <= 1) { pointsInside++; } } double piApproximation = 4.0 * pointsInside / numPoints; return piApproximation; } int main() { int numPoints = 100000000; auto start = std::chrono::high_resolution_clock::now(); double result = calculatePi(numPoints); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> duration = end - start; std::cout << "pi: " << result << std::endl; std::cout << "time_consume: " << duration.count() << " s" << std::endl; return 0; }