|
From: Per W. <pw...@ia...> - 2003-04-02 23:33:54
|
Just for the fun of it, I tested the previous code you sent.
One million calls (i=0..999999) resulted in:
Ioannis with malloc itoa(int) 4536 ms
Ioannis with auto-buf itoa(int,char*) 661 ms
itoa using sprintf and auto-buf itoa(int,char*) 1512 ms
DevStudio built-in and auto-buf _itoa(int,char*,int) 481 ms
The malloc()/free() code took 6.9 times longer than if the buffer was sent
in as a parameter - both alternatives are threadsafe. 85% of the runtime
time was malloc()/free().
That's why I try and keep an eye on heap allocations, and try for stack
buffers or buffer pools.
/Per W
On Thu, 3 Apr 2003, Ioannis Vranos wrote:
> Ok, in order to be complete (with what I consider as an itoa() without any
> specific constraint requirements) I repost a complete itoa(), with the few
> bugs fixed. The implementation was influenced by the spirit "(Real
> programmers) Don't comment their code. If it was hard to write, it should be
> hard to
> understand and even harder to modify." See the attached file.
>
>
> #include <stddef.h>
> #include <stdlib.h>
> #include <stdio.h>
>
>
> char *itoa(int i)
> {
> size_t Length;
> char *p;
> int temp=i;
>
> int sign=temp<0?-1:1;
>
> if(!sign)
> {
> p=malloc(2);
>
> if(!p)
> return NULL;
>
> p[0]='0', p[1]=0;
>
> return p;
> }
>
> temp=sign*i;
>
> for(Length=0; temp/=10; Length++)
> ;
>
> p=malloc(Length+1+!sign==1);
>
> if(!p)
> return NULL;
>
> sprintf(p, "%d", i);
>
> return p;
> }
>
>
>
> Ioannis Vranos
>
> * Programming pages: http://www.noicys.freeurl.com
> * Alternative URL: http://run.to/noicys
>
|