decreasing time it takes to run my program in c

liwandong0612 注册会员
2023-01-25 16:47

Here some suggestions:

  1. I think you should pre-calculate the required size of your *graf memory instead of reallocating it again and again. By using a prealloc_graf function for example.
    • You will get some great time improvement since reallocating is time-consuming especially when it must actually move the memory.
    • You should do this method especially if you are working with big files.
    • And since you're working with files, pre-calculating should be done easily.
  1. It is important to check for successful memory allocation before trying to use the said memory because allocation function can fail.

  2. Finally, some changes for the init function :

void init(przejscie_t **graf, int vp, int n) {
    *graf = realloc(*graf, (vp + 1) * sizeof(przejscie_t));
    // The `if` statement was redundant.
    // Added a ternary operator for ``n == -1``.
    // Alternatively, you could use ``n = (n == -1 ? vp : n)`` right before the loop.
    for (int i = (n == -1 ? vp : n); i <= vp; i++) {
        (*graf)[i].l = 1;
        // (*graf)[X].l is is always 1.
        // There is no reason to use (*graf)[X].l * sizeof(int) for malloc.
        (*graf)[i].node = malloc(sizeof(int));
        (*graf)[i].waga = malloc(sizeof(int));

I've commented everything that I've changed but here is a summary :

  • The if statement was redundant.
    • The for loop cover all cases with ternary operator for n equals -1.
    • The code should be easier to understand and to comprehend this way.
  • The node and waga arrays were not being initialized "properly". Since l is always equals 1 there was no need for an additional operation. This doesn't really change execution time tho since its constant.
  1. I would also suggest that your "functions running allocation functions" should return a boolean saying if the function succeeded. In the case the allocation failed you can return false to say that your function failed.

About the Author

Question Info

Publish Time
2023-01-25 16:47
Update Time
2023-01-25 16:47