This question pertains to ANSI C. I think that it should be a simple answer...so which of these methods is the fastest? It doesn't really have anything to do with my current projects but it just came to mind one day and I didn't see the answer right away on the web...
preguntado el 31 de julio de 12 a las 14:07
printf is by far preferable, by many orders of magnitude and in every sense. It is a library function that's part of the C standard, and it makes your own program print the desired output.
system on the other hand launches a new, separate process (something that takes a comparable eternity), and you still have to hope that your shell actually provides an
echo command that does the same thing.
La única cosa peor que llamar
echo sería llamar
system to invoke a compiler that compiles another program that contains
printf and run that, I guess...
system spawns a shell to execute your command. This means that there is a
fork()/exec() to spawn the shell and the shell in turn calls another
echo. Por no mencionar el
shell has to search the
echo, pass around environment variables etc.
Terribly, terribly slower than a function call to
printf. This is besides the fact that
system may fail because there is no shell, or no
It would has been better in this case to make comparison of what is comparable... you can call something like a printf in system(), and not only processor is involved in the fastness.
In some specific cases, i believe that it's not impossible that a call to printf would be slower than calling a new small process (but it suppose to own a bizarre configuration processor vs hdd/memory).
In the same process, using a system_call is the fastest way to write something... (without buffer issues).
In most unix system for instance, a write call (if the only need is to write a simple string) is the fastest way.
system may not be able to find the
echo command/program ... or someone with knowledge of your code could install a malicious program named
echo on his/her path. So, not only is
system going to be orders of magnitude slower, it's a security risk.
If you find yourself in a situation where you have to use
system, tiene que siempre fully qualify the command you're calling (e.g.
But you should never need to use it. Anything that you can invoke an external program to do ... you should be able to find a library (or code with which you can build a library) that you can invoke from your program to do the same thing. And it will be much faster and safer that way.