Bizzu Bizzu - 28 days ago 9
C Question

How to measure the quality of my code?

I have some experience with coding but one of the biggest questions which annoying me is how to improve my code.

I every time check the complexity, readability and the correctness of the code but my question is how I can measure the size and the time of specific commands.

For example:

when I have the next problem:

A
is an integer

B
is an integer

C
is an integer

if
- A is bigger the B assign
C=A


else
-
C=B


for that problem, we have 2 simple solutions -

1. use if-else statement

2. use ternary operator

for a dry check of the size of the file before compilation, i get that the second solution file is less from the first in a half (for 1000000 operations I get a difference of some MB).

My question is how I can measure the time difference between some codes which make the same operation but with different commands, and how much the compiler makes optimization for commands which is close like the 2 from the example.

Answer Source

Analyse the Time Complexity of the two algorithms. If they seem competitive,

Benchmark.

Provide a sufficient large input for your problem, so that the timing is not affected by other -OS- overheads.

Develop two programs that solve the same problem, but with a different approach.

I have some methods in Time measurements to time code. Example:

#include <sys/time.h>
#include <time.h>

typedef struct timeval wallclock_t;

void wallclock_mark(wallclock_t *const tptr)
{
    gettimeofday(tptr, NULL);
}

double wallclock_since(wallclock_t *const tptr)
{
    struct timeval  now;
    gettimeofday(&now, NULL);

    return difftime(now.tv_sec, tptr->tv_sec)
            + ((double)now.tv_usec - (double)tptr->tv_usec) / 1000000.0;
}

int main(void)
{
    wallclock_t  t;
    double  s;

    wallclock_mark(&t);

    /*
     * Solve the problem with Algorithm 1
    */

    s = wallclock_since(&t);
    printf("That took %.9f seconds wall clock time.\n", s);
    return 0;
}

You will get a time measurement. Then you use solve the problem with "Algorithm 2", for example, and compare these measurements.


PS: Or you could check the Assembly code of every approach, for a more low level approach.