c - Most efficient method to print "test"? -
to print while consuming least amount of resources.
it can 0 or 1 not test
fputs("test",stdout); printf("%s", "test"); puts("test"); which 1 of above commands efficient ?
is there else more efficient ?
there 2 answers here.
(1) practical purposes, there no difference in performance (time or other resources used) between
puts("test"); fputs("test\n",stdout); printf("%s\n", "test"); fprintf(stdout, "%s\n", "test"); (there few differences respect newline handling, shown.)
use whichever 1 clearest , makes sense program; don't worry efficiency here.
(2) question of form "which of these fastest?" can answered in context of particular environment, , cannot in general predicted. if care, have no other option perform empirical test, in exact environment. beware since differences in performance slight @ best (see answer 1), may have perform thousands or millions of tests in order statistically significant answer -- , pretty reinforces point that, practically, differences don't matter.
now, fun, ran test. here little program test 4 alternatives, along low-level write system call:
#include <stdio.h> #include <time.h> int main() { int count = 100000000; time_t t1, t2; int delta; int i; t1 = time(null); for(i = 0; < count; i++) puts("test"); t2 = time(null); delta = (int) t2 - t1; fprintf(stderr, "test 1: %d secs (%f prints/sec)\n", delta, (double)count/delta); t1 = t2; for(i = 0; < count; i++) fputs("test\n", stdout); t2 = time(null); delta = (int) t2 - t1; fprintf(stderr, "test 2: %d secs (%f prints/sec)\n", delta, (double)count/delta); t1 = t2; for(i = 0; < count; i++) printf("%s\n", "test"); t2 = time(null); delta = (int) t2 - t1; fprintf(stderr, "test 3: %d secs (%f prints/sec)\n", delta, (double)count/delta); t1 = t2; for(i = 0; < count; i++) fprintf(stdout, "%s\n", "test"); t2 = time(null); delta = (int) t2 - t1; fprintf(stderr, "test 4: %d secs (%f prints/sec)\n", delta, (double)count/delta); t1 = t2; for(i = 0; < count; i++) write(1, "test\n", 5); t2 = time(null); delta = (int) t2 - t1; fprintf(stderr, "test 5: %d secs (%f prints/sec)\n", delta, (double)count/delta); } you notice have chosen run each test one hundred million times. (i wasn't kidding when said "you may have perform thousands or millions of tests".) nevertheless, here results:
test 1: 9 secs (11111111.111111 prints/sec) test 2: 8 secs (12500000.000000 prints/sec) test 3: 17 secs (5882352.941176 prints/sec) test 4: 16 secs (6250000.000000 prints/sec) test 5: 45 secs (2222222.222222 prints/sec) so, in 1 sense, answer (1) wrong. there difference: puts , fputs twice fast printf , fprintf, @ least on machine. fact had call them hundred million times in order see difference shows that, on modern machine, if you're making few tens or hundreds or thousands or millions or tens of millions of calls, won't see difference @ all.
[p.s. test program isn't strictly portable. should have used long int counter.]
Comments
Post a Comment