[英]How do I make my C program run faster?
我知道这与编译器有关,但是我完全不知道下一步该怎么做。 我正在使用一个简单的蒙特卡洛方法pi计算器,尽管C应该快得多,但我发现节点的速度比C快2倍左右。
我究竟应该怎么做才能在运行时优化C版本以提高速度? 这是我的代码,以防万一我错过了一些东西。
蒙特卡洛皮
#include <stdio.h>
#include <stdlib.h>
int main() {
int squareLen = 500;
int squareArea = squareLen * squareLen;
int radius = squareLen / 2;
int radiusSqu = radius * radius;
int x, y;
int nInRad = 0, nTotal = 0;
double pi;
while(1) {
nTotal += 1;
x = abs((rand() % squareLen) - radius);
y = abs((rand() % squareLen) - radius);
if ((x*x) + (y*y) <= radiusSqu) {
nInRad += 1;
}
if(nTotal % 100000000 == 0) {
pi = ((double) nInRad / (double) nTotal) * squareArea / radiusSqu;
printf("%lf\n", pi);
printf("%d million monte carlo points\n\n", (nTotal / 1000000));
}
}
}
monteCarloPi.js
var nIn = 0, nTotal = 0;
monteCarlo();
function monteCarlo() {
while(true){
nTotal++;
var xAbs = Math.abs((Math.random() * 500) - 250);
var yAbs = Math.abs((Math.random() * 500) - 250);
if((xAbs*xAbs) + (yAbs*yAbs) <= 250*250) {
nIn++;
}
if(nTotal % 100000000 == 0) {
console.log(((nIn / nTotal) * 500 * 500) / (250*250));
console.log((nTotal / 1000000) + ' million points');
console.log('\n');
}
}
}
当您的C代码使用-O3 -march=native
优化进行编译时,它的运行速度(比我的机器快28%)比JavaScript版本快。
gcc -O3 -march=native -Wall -Wextra -o monteCarloPi monteCarloPi.c
我的问题是我应该怎么做才能在运行时优化C版本以提高速度?
确保在编译期间使用-O3命令行参数启用了优化。
您应该重复测试足够的时间以确保结果可靠。
您应该避免任何日志记录/打印,因为这是一个很大的噪音因素。
这是我的代码,以防万一我错过了一些东西。
您看到非常相似的结果的主要原因是因为rand()
调用非常昂贵,并且在C和JS中花费大约相同的时间。 如果您可以避免在循环中进行此调用,那么您会立即看到支持C的区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.