这段代码执行Haversine距离计算,是一个更大项目的一部分。
Java实现似乎比Python快60倍。它们的实现几乎完全相同。
这个性能测试是在同一台机器和操作系统上进行的。我尝试了各种组合:
- 操作系统:Linux和Windows
- 使用不同CPU的机器(来自第四代和第六代的i5)
但执行速度的差异保持一致。
Python实现:
from math import radians, sin, cos, sqrt, asin
import time
def haversine(lat1, lon1, lat2, lon2):
R = 6372.8 # Earth radius in kilometers
dLat = radians(lat2 - lat1)
dLon = radians(lon2 - lon1)
lat1 = radians(lat1)
lat2 = radians(lat2)
a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
c = 2*asin(sqrt(a))
return R * c
start_time = time.time()
#START: Performance critical part
for x in range(1, 1*1000*1000*10):
haversine(36.12, -86.67, 33.94, -118.40)
#END: Performance critical part
elapsed_time = time.time() - start_time
print("Python elapsed time = " + str(elapsed_time)+" seconds")
Java实现:
import java.util.Date;
public class HaversineTest {
public static final double R = 6372.8; // In kilometers
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
public static void main(String[] args) {
int loopCount = 1*1000*1000*10;
long start_time = new Date().getTime();
for(int i=0;i<loopCount;i++){
haversine(36.12, -86.67, 33.94, -118.40);
}
long end_time = new Date().getTime();
long elapsed_time=end_time-start_time;
System.out.println("Java elapsed time = "+elapsed_time+" ms");
}
}
版本:
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
输出:
Java 耗时 = 229 毫秒
Python 耗时 = 15.028019428253174 秒
我能提高 Python 性能吗?
numpy
库并向量化计算。请参阅Fast Haversine Approximation (Python/Pandas)。希望纯Python能与任何编译语言竞争是徒劳的,这个展示了Python在多个方面上与Java相比表现不佳。它们各自擅长不同的领域。 - roganjosh