Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk print vs printf functions

Tags:

io

printf

awk

In awk there are two output functions: print and printf.

  • Are their implementations in awk very different?
  • What are the differences regarding performance/speed (if possible — theoretical, not only with "time" on command line)?
  • Do they use the same system calls?
like image 936
static Avatar asked Sep 06 '12 22:09

static


People also ask

What is the difference between print and printf?

The difference between printf and print is the format argument. This is an expression whose value is taken as a string; it specifies how to output each of the other arguments. It is called the format string. The format string is very similar to that in the ISO C library function printf() .

What is awk '{ print $4 }'?

The AWK language is useful for manipulation of data files, text retrieval and processing. -F <value> - tells awk what field separator to use. In your case, -F: means that the separator is : (colon). '{print $4}' means print the fourth field (the fields being separated by : ).

What does awk '{ print $2 }' mean?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

What does awk print do?

Default behavior of Awk: By default Awk prints every line of data from the specified file. In the above example, no pattern is given. So the actions are applicable to all the lines. Action print without any argument prints the whole line by default, so it prints all the lines of the file without failure.


1 Answers

  1. The performance difference is probably not measurable.
  2. The print function outputs a newline at the end; printf does not unless requested.
  3. The print code converts the arguments to strings and then sends them to the output separated by the OFS (output field separator).
  4. The printf code might need to convert the string to a double before formatting it using a double format (%16.8g or something), and similar operations.
  5. The system call used is going to write(2) or something similar for both, but there'll be code (probably <stdio.h>) layered above that.

All that adds up to:

  • The implementations are different; print is a little simpler (and therefore faster) than printf.
  • The difference is probably not measurable for most purposes.
  • Use print if it will do what you need; use printf when it does what you need.
  • Don't worry about it.

And using a sprintf followed by print is likely to be slower than using printf directly, so don't.

In case of doubt, measure.

like image 173
Jonathan Leffler Avatar answered Oct 26 '22 19:10

Jonathan Leffler