Home > database >  Why is C slower than C when doing literaly nothing
Why is C slower than C when doing literaly nothing

Time:04-19

C is almost 4 times slower than C at doing nothing (at least on my machine). When the following file is compiled by g , it is 2 times slower than with gcc:

int main() {}

With time sh -c 'for i in $(seq 0 1000) ; do ./a.out ; done, I get 0.515s for the C version, and 2s for the C one. Why is that?

There isn't a single thing done in this program, and the disassembled program is basically the same in both versions, so why is the C version roughly 4 times slower?

My guess is that the C library takes a longer time to load, but the assembly is so similar that I can't think of a reason for C to be so much slower.

CodePudding user response:

C standard library initial startup is heavier than the C runtime.

C ABI needs to initialize some structures for basic language features. Mutex locks for thread-safe initialization of data, exeptions, thread local storage, RTTI, etc.

This is why an empty executable created with a C compiler will start slower than an empty C program. As well as an empty program created with Assembly language will start much faster then a similar program created with C with a full-featured C runtime (CRT, GNU LIBC, etc).

CodePudding user response:

In fact, you compare nothing at all, because your program does nothing at all. What you got is not the program execution time, which in your case is null, but the process execution time, ie load run terminate, which is longer if your program needs more resources.

Some numbers could lead some light on this:

say we have emptyc and emptycpp, respectively compiled with gcc-10.3 and g -10.3

On my system:

  • emptyc:

    • file size: 13232
    • elf dynamic section: 17 entries (1 shared lib)
    • truss syscall report: 48 syscalls including 6 open and 11 mmap
  • emptycpp

    • file size: 13312
    • elf dynamic section: 20 entries (4 shared libs)
    • truss syscall report: 88 syscalls including 15 open and 29 mmap

Conclusion:

A program compiled with g needs more resources than the same program compiled with gcc. A process generating 88 syscalls is probably slower than a process generating 48.

  • Related