Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing multiple integers at the same time

Tags:

c

printf

I was wondering if there is a better way to print an array of ints in c;

At the moment I do a printf("%d" ,.. ) for every int in my array.

However this causes one system call per int? (if my understanding is correct).

It would be better to convert the int array to string buffer and then print the buffer in one call.

I can write the code for it if necessary.

Q1. is this a good idea or too much hassle to be worth it?

Q2. Are there any libraries that implement such a thing. (Whatever I google comes back to beginners tutorials for printing integers :s)

Edit The size of the array is not known before hand.

like image 281
Osama Javed Avatar asked Apr 29 '13 03:04

Osama Javed


1 Answers

No, it does not cause one system call per int, unless you set stdout to unbuffered mode. This is the whole point of stdio: to buffer output for you so you don't have to do it yourself. There is a minimal amount of additional call overhead for the printf function itself. If you find yourself needing more performance, you could try something like:

for (i=0; i+4<=N; i+=4)
    printf("%d %d %d %d ", a[i], a[i+1], a[i+2], a[i+3]);
for (; i<N; i++)
    printf("%d ", a[i]);
like image 143
R.. GitHub STOP HELPING ICE Avatar answered Oct 01 '22 01:10

R.. GitHub STOP HELPING ICE