简体   繁体   中英

Optimize mathematical operations in c

I am registered in a web programming c where several algorithmic exercises. I made a very simple problem is as follows: I receive 4 numbers that determine coordinates of 2 corner of a rectangle and have to calculate the area. There is a set of tests and when the second corner is below or to the left of the first (x1> x2 || y1> y2) the program exits. 在此处输入图片说明

Exemple:

Input:

1 1 4 3
0 0 1 1
9 7 3 6 //Exit

Output:

6
1

This is my code.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    while(1) {
        int x1, x2, y1, y2;
        scanf("%d %d %d %d", &x1, &y1, &x2, &y2);//x1 y1 == A, x2 y2 == B
        if(x1 > x2 || y1 > y2)
            return 0;
        printf("%d\n", (x2 - x1) * (y2 - y1));
    }
}

My question is simply a curiosity. I solved the problem with a time of "0052", and there are 3 people in front of me that have managed to solve in "0048" and "0024"!. What optimicazion methods can I use to get lower time? Probably pointers?

Some thoughts:

  1. You could use gcc's __builtin_expect() functions to make sure that the conditional is assumed to be false.

  2. It's very unlikely that pointers would help you improve your solution.

  3. scanf() is probably the really slow part. Rewriting this with a parser that only expected decimal integers would probably be much faster. Currently, scanf() needs to parse the format string, and the input number could be octal, hexadecimal, or decimal. Or could be invalid input. etc.

Not much, but maybe try declaring int x1, x2, y1, y2; before entering the loop.

Here are my suggestions:

  1. in the compile statement use:

     gcc -O3 
  2. place all working variables in global space rather than stack space

     int x1, x2, y1, y2;, area char buffer[100]; int main() { do { fgets( buffer, sizeof(buffer), stdin ); sprintf( buffer, "%d %d %d %d", &x1, &y1, &x2, &y2); x2-=x1; y2-=y1; area = y2*x2; printf("%d\\n",area); // or perhaps puts( itoa(area) ); } while(( 0 <= x2) && (0 <= y2) return(0); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM