實驗實測乘法運算如果是整數倍的時候,使用連續乘法的效能遠高於使用pow函數的運算效能。

 

 

實驗過程發現,由於基本運算的速度過快,用時間函數很難看到運算速度快慢產生的時間差。

因此設置了MAG 常數放大運算速度的落差,方便觀察。

 

實驗使用C++ 進行測試,程式碼如下:


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <math.h>

#define MAG  1000000

using namespace std;

void time_start();
void time_end(char*);

double START,END;
    
int main(){
	int a = 554464;
	float b = 0.76546;
	
	time_start();
	int a_2 = 0;
	float a_2_p = 0.0;
	float b_2 = 0.0;
	float b_b_p = 0.0;
	
	for (int i=1;i<=MAG;i++) a_2 += a * a;
	time_end("a*a, ");
	
	time_start();
	for (int i=1;i<=MAG;i++) a_2_p += pow(a,2);
	time_end("pow(a,2), ");
	
	time_start();
	for (int i=1;i<=MAG;i++) b_2 += b * b;
	time_end("b*b, ");
	
	time_start();
	for (int i=1;i<=MAG;i++) b_b_p += pow(b,2);
	time_end("pow(b,2), ");
	return 0;
}

void time_start(){
	START = clock();
}
void time_end(char *str){
    END = clock();
    cout << endl << str << "進行運算所需花費的時間"" << (END - START) / CLOCKS_PER_SEC << " S" << endl;
}

 

實驗結果如下圖,從結果來看約有10倍的速度差異。

 

 

專案連結

 
arrow
arrow
    文章標籤
    c c++
    全站熱搜

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()