Denis Balan
Denis Balan

Reputation: 198

Why the same code running time differs?

Making a benchmark, i have tested and figured out interesting results.

//gcc -o code_in_c.exe code_in_c.c
#include <stdio.h>
int main() {
    int a, b, c, d, r;
    while (scanf("%d %d %d %d", &a, &b, &c, &d) != -1){
        r = a + b * c + d;
        printf("%d\n", r);
    }
    return 0;
}

and second file for cpp

//g++ -o code_in_cpp.exe code_in_cpp.cpp
#include <cstdio>
int main(){
    int a, b, c, d, r;
    while (scanf("%d %d %d %d", &a, &b, &c, &d) != -1){
        r = a + b * c + d;
        printf("%d\n", r);
    }
    return 0;
}

it's the same code, except for first two lines. the program need to read 4 integers from every line perform arithmetic operations (multiply two integers from middle) and add from margins

1 2 3 4 -> 1 + (2 * 3) + 4 -> 1 + 6 + 4 -> 11

so, testing this with random numbers on a 150 000 lines give me results for cpp

Running "code_in_cpp.exe", press ESC to terminate...
Program successfully terminated
  exit code:     0
  time consumed: 2.37 sec
  time passed:   4.34 sec
  peak memory:   2162688 bytes

and for c.

Running "code_in_c.exe", press ESC to terminate...
Program successfully terminated
  exit code:     0
  time consumed: 2.87 sec
  time passed:   4.57 sec
  peak memory:   2162688 bytes

So my question is what depends on running time?

(both was running on same machine)

Upvotes: 0

Views: 276

Answers (3)

Patrick Fernandes
Patrick Fernandes

Reputation: 36

In current OS's, program execution time is mostly a non-deterministic variable, meaning that even if you run the same C code twice, it could run in different time, depending on CPU usage and ocupation by the OS, memory management and current ocupation (does OS's uses cache in one of the executions?), etc... Also, as other users pointed out, it probably also depends on the implementation of standart libraries, since, although very similar, they are different languages.

Upvotes: 1

user3639612
user3639612

Reputation: 61

I think it's because the g++ links with the C++ standard libraries where the implementation of some functions may be slightly different from the C standard library implementation.

C++ standard library is backwards compatible with the C standard library but this doesn't mean there can't be performance improvements seen.

Upvotes: 1

Mohsen Bahaloo
Mohsen Bahaloo

Reputation: 287

this time is depend on very things like: OS context switch, memory management mechanism in OS , mechanism of runnig process (multi thread, multi core cpu , ...)

so, if we run one program 2 times, necessarily there is no reason that execution time of them become equal.

Upvotes: 3

Related Questions