Categories
不学无术

除法的效率

估计应该都知道算除法的效率比算+-*低好多,那么到底低多少呢?简单写了一个程序测试看看。
注意:avg0函数可能会碰到溢出的情况,这种方法尽量不要用。

  • avg0: 统一加起来,再做除法;
  • avg1: 加的时候就做除法;
  • avg2: 加的时候乘以预先算好的,分母的倒数;
void printDuration(clock_t start, clock_t end){
    cout << "Time elapsed: " << (end - start)/(float)CLOCKS_PER_SEC << " seconds." << endl;
}
double avg0(int* ary, int N, long again){
    cout << "avg0: ";
    clock_t start = clock();
    double sum;
    while(again > 0){
        sum = 0;
        for(int i=0; i<N; i++)
            sum += ary[i];
        sum /= (double)N;
        again --;
    }
    clock_t end = clock();
    printDuration(start, end);
    return sum;
}
double avg1(int* ary, int N, long again){
    cout << "avg1: ";
    clock_t start = clock();
    double sum = 0;
    while(again > 0){
        for(int i=0; i<N; i++)
            sum += ary[i]/(double)N;
        again--;
    }
    clock_t end = clock();
    printDuration(start, end);
    return sum;
}
double avg2(int* ary, int N, long again){
    cout << "avg2: ";
    clock_t start = clock();
    double sum = 0;
    while(again > 0){
        double denominator = 1 / (double)N;
        for(int i=0; i<N; i++)
            sum += ary[i] * denominator;
        again--;
    }
    clock_t end = clock();
    printDuration(start, end);
    return sum;
}
int main() {
    int N;
    long again;
    cin >> N >> again; //num of numbers to be generated
    srand(time(NULL));
    int* ary = new int[N];
    for(int i=0; i<N; i++)
        ary[i] = rand();
    double r0 = avg0(ary, N, again);
    double r1 = avg1(ary, N, again);
    double r2 = avg2(ary, N, again);
    return 0;
}

结果:

50000 50000
avg0: Time elapsed: 7.49197 seconds.
avg1: Time elapsed: 16.7689 seconds.
avg2: Time elapsed: 7.51349 seconds.
Process finished with exit code 0

比一倍还多的时间!可怕!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.