Python 與C++的比較
語言速度比較
在Python中利用numpy, SciPy宣告陣列, 並記錄所需時間
Example Code
- import numpy as np
- import scipy as sp
- import time
- from array import array
-
- n=1500
- tStart = time.time()
- x = array( 'd' )
- for i in range( n ):
- x.append( i*8e-10 )
- tEnd = time.time()
- print ("append method: It cost %f sec", tEnd - tStart)
-
- tStart = time.time()
- a = range(1, 1500)
- [x*8e-10 for x in a]
- a = np.array(a)
- tEnd = time.time()
- print ("declare a range and convert to np.array: It cost %f sec", tEnd - tStart)
- tStart = time.time()
- a = range(1, 1500)
- [x*8e-10 for x in a]
- a = sp.array(a)
- tEnd = time.time()
- print ("declare a range and convert to sp.array: It cost %f sec", tEnd - tStart)
-
- tStart = time.time()
- x2 = np.arange(0, 1.2*10e-6, 8e-10)
- tEnd = time.time()
- print ("NumPy: It cost %f sec", tEnd - tStart)
-
- tStart = time.time()
- x2 = sp.arange(0,1.2*10e-6,8e-10)
- tEnd = time.time()
- print ("Scipy: It cost %f sec", tEnd - tStart)
Note and Comments
- import numpy as np: 引入numpy 數值分析函式庫
- import scipy as sp: 引入scipy 分析函式庫, scipy 是優化並擴充版本的numpy
- import time: 引入時間函式庫time, 可取得系統時間,與各種時間處理函數
- from array import array: 引入矩陣函式庫
-
- 以下為宣告一個array物件, 並在尾端加入一個新的元素, 直到1500元素為止
- n=1500
- tStart = time.time(): time.time() 取得目前時間並存入tStart
- x = array( 'd' ): 宣告一個倍精度浮點數的array
- for i in range( n ): for迴圈, 累計n圈
- x.append( i*8e-10 ): 每次都在x array末端新增一個浮點元素
- tEnd = time.time()
- print ("append method: It cost %f sec", tEnd - tStart): 輸出時間差在螢幕上
-
- tStart = time.time()
- a = range(1, 1500): 產生一個 0到1499的整數list
- [x*8e-10 for x in a]: List comprehension, 將a list中的每一個元素乘上一個浮點數
- a = np.array(a): 利用numpy函式庫將a lst 轉為 a array
- tEnd = time.time()
- print ("declare a range and convert to np.array: It cost %f sec", tEnd - tStart)
- tStart = time.time()
- a = range(1, 1500)
- [x*8e-10 for x in a]
- a = sp.array(a) 利用scipy函式庫將a lst 轉為 a array
- tEnd = time.time()
- print ("declare a range and convert to sp.array: It cost %f sec", tEnd - tStart)
-
- tStart = time.time()
- x2 = np.arange(0, 1.2*10e-6, 8e-10) 利用Numpy函式庫中的arange函式, 產生1500個間隔爲8e-10的浮點 array
- tEnd = time.time()
- print ("NumPy: It cost %f sec", tEnd - tStart)
-
- tStart = time.time()
- x2 = sp.arange(0, 1.2*10e-6, 8e-10) 利用Scipy函式庫中的arange函式, 產生1500個間隔爲8e-10的浮點 array
- tEnd = time.time()
- print ("Scipy: It cost %f sec", tEnd - tStart)
how to run the py code with the console 如何執行程式
- 將code 存入一個以.py為附檔名的檔案, 例如pythonOpen.py. 在命令列中打入python pythonOpen.py 執行程式
result
利用c++ 宣告一個包含1500個元素的一維矩陣
Example Code
- #include
- #include
- using namespace std;
-
- int main()
- {
-
- double x[1500];
- clock_t start = clock();
- for(int i=0; i<0; i++ )
- {
- x[i] = i * 8E10;
- }
- clock_t end = clock();
- double time = static_cast<double>(end-start)/CLOCKS_PER_SEC;
- std::cout << "time = " << time << std::endl;
- }
how to run the py code with the console 如何執行程式
- 將code 存入一個以.cc為附檔名的檔案, 例如runC.cc . 在命令列中打入g++ runC.cc 編譯程式碼, c++將自動將可執行的程式碼輸出爲 a.out
- ./a.out 執行程式
result