[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9
From: |
Bruno Haible |
Subject: |
Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9 |
Date: |
Wed, 22 Dec 2010 22:47:53 +0100 |
User-agent: |
KMail/1.9.9 |
Eric Blake wrote:
> one _very_ common use of snprintf is to call it with size 0 to see
> how much to allocate, then allocate and call again.
Why do people do this? It appears to be slower than just calling
asprintf, because it has to parse the format string and produce
the expansion twice.
====================== foo.c ==========================
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int REPEAT = atoi (argv[1]);
int ALGO = atoi (argv[2]);
const char *fmt = "%d";
int arg1 = 12345;
if (ALGO == 0)
{
int repeat;
for (repeat = REPEAT; repeat > 0; repeat--)
{
int len = snprintf (NULL, 0, fmt, arg1);
char *mem = malloc (len + 1);
snprintf (mem, len + 1, fmt, arg1);
free (mem);
}
}
else
{
int repeat;
for (repeat = REPEAT; repeat > 0; repeat--)
{
char *mem;
if (asprintf (&mem, fmt, arg1) < 0)
abort ();
free (mem);
}
}
return 0;
}
==============================================================================
I get timings like
$ time ./a.out 10000000 0
real 0m4.253s
user 0m4.248s
sys 0m0.004s
$ time ./a.out 10000000 1
real 0m4.035s
user 0m4.028s
sys 0m0.004s
That is, snprintf + malloc + snprintf is slower than asprintf.
Bruno
- [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Paul Eggert, 2010/12/21
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Bruno Haible, 2010/12/21
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Bruno Haible, 2010/12/21
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Eric Blake, 2010/12/21
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Paul Eggert, 2010/12/21
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9, Bruno Haible, 2010/12/22
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Paul Eggert, 2010/12/22
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Paul Eggert, 2010/12/24
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9,
Bruno Haible <=
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ... ) to Solaris 8 and 9, Jim Meyering, 2010/12/22
- Re: [PATCH] snprintf: port snprintf (NULL, 0, ...) to Solaris 8 and 9, Paul Eggert, 2010/12/22