lua-users home
lua-l archive

Re: bottleneck: string2hex

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great Valerio Schiavoni once stated:
> Hello,
> profiling my application, the big bottleneck of it comes from this function:
> 
> function string2hex(str)
> assert(str,"String2hex got null argument")
> local h,s = string.gsub(str, "(.)", function(c) return
> string.format("%02X", string.byte(c)) end)
> return h
> end
> 
> 
> The size of input strings can be from 1kb to 1Mb.
> How would you optimize it ?
 I'd try some Lua variants and if it still proved too slow, I would
probably test a C implementation. Which I did. Test harness:
start = os.clock()
h = string2hex(data)
stop = os.clock()
print("string2hex()",stop - start)
start = os.clock()
h = strhex(data) -- C version
stop = os.clock()
print("strhex()",stop - start)
[spc]lucy:/tmp>lua tlua.lua
string2hex1() 3.52
strhex() 0.65
[spc]lucy:/tmp>
C code is as follows:
/*
 * Sample code---feel free to use.
 *
 * compiled and tested under Linux
 * gcc -Wall -Wextra -pedantic -ansi -g -shared -fpic -o strhex.so strhex.c
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h> 
static int strhex(lua_State *L)
{
 const char *s;
 size_t size;
 size_t max; 
 char *ns; 
 char *p; 
 
 s = luaL_checklstring(L,1,&size);
 ns = malloc((size * 2) + 1);
 for ( p = ns , max = size ; max > 0 ; max--)
 {
 sprintf(p,"%02X",*s++);
 p += 2;
 }
 
 lua_pushlstring(L,ns,size * 2);
 free(ns);
 return 1;
}
 
int luaopen_strhex(lua_State *L)
{
 lua_register(L,"strhex",strhex);
 return 0;
}
 Then again, I've been programming in C for years now, so this type of
stuff is second nature to me.
 -spc

AltStyle によって変換されたページ (->オリジナル) /