我這里用的Python環境是Anaconda3 2019.7
這里測驗的程式是找出所有1000以內的勾股數,
a∈[1, 1000],b∈[1, 1000], c∈[1, 1000]
滿足a2 + b2 = c2 有多少種解?
如果用普通的python去寫,代碼如下:
創建一個main.py
# encoding=utf-8
# cython: language_level=3
import time
import pyximport
pyximport.install()
import pyth_triples
def main():
start = time.time()
result = pyth_triples.count_triples(1000)
duration = time.time() - start
print(result, duration * 1000, "ms")
if __name__ == '__main__':
main()
創建pyth_triples.py
# encoding=utf-8
# cython: language_level=3
def count_triples(limit):
result = 0
for a in range(1, limit + 1):
for b in range(a + 1, limit + 1):
for c in range(b + 1, limit + 1):
if c ** 2 > a ** 2 + b ** 2:
break
if c ** 2 == (a ** 2 + b ** 2):
result += 1
return result
這時候還沒有編譯成C去運行,只是從pyx檔案匯入函式去使用,
執行結束以后,結果為881,耗時為57603毫秒,太慢了,

現在開始,我們編譯成C語言去運行,看一下效果,
修改pyth_triples.pyx檔案,定義的變數都改為cdef int xxx = 0
# encoding=utf-8
# cython: language_level=3
def count_triples(limit):
cdef int result = 0
cdef int a = 0
cdef int b = 0
cdef int c = 0
for a in range(1, limit + 1):
for b in range(a + 1, limit + 1):
for c in range(b + 1, limit + 1):
if c ** 2 > a ** 2 + b ** 2:
break
if c ** 2 == (a ** 2 + b ** 2):
result += 1
return result
創建setup.py (這一步其實可以不做,因為這只是把編譯結果寫入本地磁盤,給我們展示生成的C語言代碼長什么樣)
# encoding=utf-8
# cython: language_level=3
from distutils.core import setup
from Cython.Build import cythonize
# set PYTHONHOME=D:\Anaconda3
# conda activate
# python setup.py build_ext --inplace
setup(
ext_modules=cythonize("pyth_triples.pyx")
)
依次在pycharm的終端執行以下命令:
set PYTHONHOME=D:\Anaconda3
conda activate
python setup.py build_ext --inplace
這將生成.c檔案和一些不知道什么檔案,

執行main.py以后,結果不變,實行時間由原來的57603毫秒減少到35毫秒左右,相差1600多倍,

如果用Java去跑這套代碼
Java代碼:
public class TriplesTest {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
System.out.println(count_triples(1000));
long endTime = System.currentTimeMillis();
System.out.println("run time:" + (endTime - startTime) + "ms");
}
public static int count_triples(int limit) {
int result = 0;
for (int a = 1; a <= limit; a++) {
for (int b = a + 1; b <= limit; b++) {
for (int c = b + 1; c <= limit; c++) {
if (Math.pow(c, 2) > Math.pow(a, 2) + Math.pow(b, 2)) {
break;
}
if (Math.pow(c, 2) == Math.pow(a, 2) + Math.pow(b, 2)) {
result += 1;
}
}
}
}
return result;
}
}
執行時間是130ms左右,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417161.html
標籤:AI
上一篇:2022年人工智能5大發展趨勢
