之前做过基本的集合操作比较,例如循环向 list 追加元素,python 比 java 快,我想可能是因为 python 的基本容器数据类型经过 C 优化导致。
再比较简单的多线程操作:1000 张票两个售票员线程卖票,结果是 python 多数在 600 多毫秒完成,java 多在 300 多毫秒多完成。
代码:
Java:
Saler.java
public class Saler extends Thread {
private String sname;
private static int tickets = 100;
final static Object lock = new Object();
Saler(String sname) {
this.sname = sname;
}
@Override
public void run() {
while (tickets > 0) {
synchronized (lock) {
if(tickets == 0){
break;
}
System.out.println(sname + " sale : " + tickets);
tickets--;
// this.yield();
}
}
}
}
App.java
public class App {
public static void main(String[] args) throws Exception {
Saler s1 = new Saler("s1");
Saler s2 = new Saler("s2");
long start = System.nanoTime();
s1.start();
s2.start();
s1.join();
s2.join();
System.out.println(System.nanoTime() - start);
}
}
python:
from time import perf_counter_ns as pc
import threading
tickets = 100
lock = threading.Lock()
class Saler(threading.Thread):
def __init__(self, sname):
super().__init__()
self.name = sname
def run(self):
global tickets
while tickets > 0:
with lock:
if tickets == 0:
break
print("{0} sales: {1}".format(self.name, tickets))
tickets -= 1
if __name__ == '__main__':
t1 = Saler('saler1')
t2 = Saler('saler2')
start = pc()
t1.start()
t2.start()
t1.join()
t2.join()
print(pc() - start)