看到一篇文章,說最近閱讀LAMMPS源碼,悟出了很多道理。在計算性能優化這塊,源代碼作者很多寫法我最初不以為意,后來發現是作者有意為之,就是為了把計算性能優化到極致。做計算仿真軟件,也特別需要注意這些吧,記錄下,在后續編碼時注意。
原文鏈接:https://mp.weixin.qq.com/s/o3tiUTUonbdHVxqczlQEZw?nwr_flag=1#wechat_redirect
1 匯總方法:
主要包括幾條:
- 能做乘法就不做除法;
- 能做平方就不做開方;
- 能做連乘就不求冪;
- 能提前算的常量就不要放到循環里算;
2 嘗試和時間對比
2.1 C++下的乘法和除法
#include <iostream>
#include <chrono>
using namespace std;
void chengfa(int a, int b, int n);
void chufa(int a, int b, int n);
int main()
{int a = 10;int b = 3;int n = 1000000;chengfa(a,b,n);chufa(a,b,n);return 0;
}void chengfa(int a,int b,int n) {int c;auto start1 = std::chrono::high_resolution_clock::now();for (int i = 0; i < n; i++){c = a * b;}auto end1 = std::chrono::high_resolution_clock::now();std::chrono::duration<double> elapsed1 = end1 - start1;cout << "執行乘法的時間:" << elapsed1.count() << "s\n" << endl;
}void chufa(int a, int b, int n) {int d;auto start2 = std::chrono::high_resolution_clock::now();for (int i = 0; i < n; i++){d = a / b;}auto end2 = std::chrono::high_resolution_clock::now();std::chrono::duration<double> elapsed2 = end2 - start2;cout << "執行乘法的時間:" << elapsed2.count() << "s\n" << endl;
}
少次計算,反倒除法快;多次,乘法顯示出了優勢;