Foros del Web » Programando para Internet » PHP »

tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

Estas en el tema de tengo un script con bucles y funciones que tarda mucho, como puedo hacer ? en el foro de PHP en Foros del Web. buenas gente ! tengo un script que hice yo, lo primero que hace es leer un archivo y luego con un for lo va pasando ...
  #1 (permalink)  
Antiguo 28/04/2008, 07:50
 
Fecha de Ingreso: marzo-2007
Mensajes: 180
Antigüedad: 17 años, 1 mes
Puntos: 0
Pregunta tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

buenas gente !
tengo un script que hice yo, lo primero que hace es leer un archivo y luego con un for lo va pasando a una matriz a diferentes columnas (hay varios if), luego de eso se trabaja con el array convirtiendo varias cosas y armando una variable que luego se pasa a un xml.

el tema es que lleva mucho tiempo y solo me lo hace con archivos de pruebas de menos de 1mb mas o menos , pero el archivo que tengo q usar pesa como 34mb, y me da tiempo excedido.
aunque le ponga el set_time_limit(0); no funciona, se queda cargando como 20 minutos y despues no hace nada.

alguna ayuda o recomendacion ?

poner una pausa o alguna manera de hacer algo para que espero, tocar un link y seguir, o algo asi ?






aca les copio el codigo de cuando pasa el archivo a array, hay cosas medias rebuscadas, pero es que era algo simple y despues se fue ampliando, encima hay manejo de caracteres raros de utf8, etc.


Código PHP:
$archivo="mw2_a_abhiks.dict";

set_time_limit(0);

$fp fopen($archivo,'r');

if (
file_exists($archivo))
{
    
$array file($archivo);

    
$newentry=0;
    
$line=0;
    
$page=1
    
$pagedict=0
    for (
$i=0;$i<count($array);$i++)
    {
        
        
$textline=$array[$i];
        
$textline=str_replace(" ,",",",$textline);
        
        
$textline3=substr($array[$i],0,2);
        if (
$textline3=='==' )
        {
            
$newentry++;
            
$line=0;
        }
        else
        {
            
$line++;
        }
        
        if (
$line==4)
        {
            ${
'matriz'.$newentry}[1]=rtrim($textline); // HK
            
if ((${'matriz'.$newentry}[1]) && (${'matriz'.($newentry-1)}[1]) && (strcmp(${'matriz'.$newentry}[1],${'matriz'.($newentry-1)}[1])==0)) // compara hk con hk anterior y resetea el newentry
            
{
                ${
'matriz'.$newentry}[6]='';
                
$newentry--;
                
$page--;
            }
            
        }
        elseif (
$line==6)
        {
            
            ${
'matriz'.$newentry}[2]=substr($textline,2,strpos($textline,"]")-2); // HK con simbolos
            
${'matriz'.$newentry}[3].="---> ".substr($textline,strpos($textline,"]")+1); // Definicion
            
$hksimbolx=rtrim(ltrim(${'matriz'.$newentry}[2]));
            
$hkraiz=strstr(makeSafeEntities($hksimbolx),"&radic;"); // toma desde la primer raiz hasta el final , √
            
$hkraiz=substr($hkraiz,8); // tomamos desde la raiz contando 8 caracteres para no tomar los caracteres del simbolo que son √ mas un espacio.
            
$hkraizlen=strlen(makeSafeEntities($hkraiz));
            
$hksimbollen=strlen(makeSafeEntities($hksimbolx));
            
$diflen=$hksimbollen-$hkraizlen;
            
$hkprevraiz=rtrim(substr(makeSafeEntities($hksimbolx),0,$diflen)); // previo hasta raiz
            
$hkprevlen=strlen($hkprevraiz);
            
$hksimbol=$hkprevraiz.$hkraiz;
            ${
'matriz'.$newentry}[4]=$hkprevraiz;
            ${
'matriz'.$newentry}[5]=$hkraiz;
        }
        if (
$line>&& $textline3!='==')
        {
            ${
'matriz'.$newentry}[3].=$textline// graba definicion
        
}
        if (
$textline3=="1[" || $textline3=="2[")
        {
            ${
'matriz'.$newentry}[0]=$page// Almacena si es una nueva pagina
            
$page++;
        }

        ${
'matriz'.($newentry)}[6].=$textline// dict orig

    
// fin for
    
    
// fin if file exists 
  #2 (permalink)  
Antiguo 28/04/2008, 08:26
Avatar de .php  
Fecha de Ingreso: julio-2006
Mensajes: 481
Antigüedad: 17 años, 8 meses
Puntos: 5
Re: tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

aca se diferencia los programadores, se llama ingenieria de software,
lo q te explican aca es como optimizar tu codigo aparte de como cobrar un software,
pero el tema es otro, yo de ti revisaria mi codigo con calma y lo programaria en otros lenguajes,
una vez esto empezaria a cambiar el codigo como por ejemplo en vez de un for utilizo un foreach
por que?? para utilizar menos variables $i, lo otro le haria una limpiaza a mi array antes de pasar al for, por que más que seguro existen espacios en blancos.
y lo otro se ve bien tu codigo, solo debes intentar de optimizar la apertura del fichero y el for.

por que lees linea por linea el fichero y lo pasas al for por cada linea.
__________________
~~[FiDeLio]~~
  #3 (permalink)  
Antiguo 28/04/2008, 08:33
 
Fecha de Ingreso: marzo-2007
Mensajes: 180
Antigüedad: 17 años, 1 mes
Puntos: 0
Exclamación Re: tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

el tema es asi, lenguajes se solamente php, y c, y algo de visual basic, pero php es lo que mas me gusta.

el archivo es un .DICT, hay que leer linea por linea porque estan relacionadas
es un diccionario, y lo que separa palabra de palabra es una linea con varios ====== , que a veces cambia el largo.
ademas la 5 linea despues de esos === empieza o con 1[ o con 2[ o con 3[ , si es 1 o 2 es una "pagina nueva" y si es 3 depende del que esta arriba, es algo muy complejo.


ahi probe dejar solo este texto que puse aca y funciono bien, pero al poner el otro codigo es cuando mas se cuelga, que ahi es cuando pasa por varias funciones mas que hacen buscar y reemplazar, convertir textos, etc.
Fatal error: Maximum execution time of 360 seconds exceeded in...


esta seria la 2da parte del archivo que ejecuto:
Código PHP:

$shtml='<?xml version="1.0" encoding="utf-8" ?><mediawiki xmlns="http://www.mediawiki.org/xml/export-0.3/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.3/ http://www.mediawiki.org/xml/export-0.3.xsd" version="0.3" xml:lang="en">
  <siteinfo>
    <sitename>Sanskrita</sitename>
    <base></base>
    <generator>MediaWiki 1.10.0</generator>
    <case>case-sensitive</case>
      <namespaces>
      <namespace key="-2">Media</namespace>
      <namespace key="-1">Special</namespace>
      <namespace key="0"/>
      <namespace key="1">Talk</namespace>
      <namespace key="2">User</namespace>
      <namespace key="3">User talk</namespace>
      <namespace key="4">Sanskrita</namespace>
      <namespace key="5">Sanskrita talk</namespace>
      <namespace key="6">Image</namespace>
      <namespace key="7">Image talk</namespace>
      <namespace key="8">MediaWiki</namespace>
      <namespace key="9">MediaWiki talk</namespace>
      <namespace key="10">Template</namespace>
      <namespace key="11">Template talk</namespace>
      <namespace key="12">Help</namespace>
      <namespace key="13">Help talk</namespace>
      <namespace key="14">Category</namespace>
      <namespace key="15">Category talk</namespace>
    </namespaces>
  </siteinfo>';
 
$page=0;
for ($x=1;$x<$newentry;$x++)
{
    $page=${'matriz'.$x}[0];
    
    if ($page) // Esto se imprime una vez por cada pagina
    {
        $pagedict=$page;
        ${dictorig.$page}.=rtrim(str_replace("---> ","->",${'matriz'.($x)}[6]));
        $key[$page]=keywordshk(${'matriz'.$x}[1]);
        if ($x>1)
        {
            $pagedicttemp=($page-1);
            $shtml.=htmlspecialchars('<!-- <mw page="'.(($page-1)*10).'"> -->');
            $shtml.=htmlspecialchars('<!-- <keywords>'.$key[$page-1].'</keywords> -->');
            $shtml.=htmlspecialchars('<!-- <link></link> -->');
            $shtml.=htmlspecialchars('<!-- <progress en="" es=""> -->');
            $shtml.="\n\n".htmlspecialchars('<!-- *** START DICT ORIGINAL ***'.${dictorig.$pagedicttemp}."\n\n".'*** END DICT ORIGINAL *** -->');
            $shtml.='</text>
    </revision>
  </page>';
        }
        $shtml=$shtml. "\n<page>\n<title>".${'matriz'.$x}[1];
        $hkraiz=${'matriz'.$x}[5];
        $hkprevraiz=trim(${'matriz'.$x}[4]); // previo hasta raiz
        $hkprevraiz=str_replace("'","",$hkprevraiz);
        $hksimbol=$hkprevraiz.$hkraiz;
        $hk=${'matriz'.$x}[1];
        $def=str_replace('&','&amp;',${'matriz'.$x}[3]);
        $def=search_and_replace($def);
        $shtml.='</title>
    <id></id>
    <revision>
      <id></id>
      <timestamp></timestamp>
      <contributor>
        <username></username>
        <id></id>
      </contributor>
      <minor/>
      <text xml:space="preserve">';
        $shtml=$shtml.impmodule($hk,$hkraiz);
        $shtml=$shtml. "\n\n";
        $shtml=$shtml. "\n" . htmlspecialchars('<html><div id="santitle"><santitle>');
        $shtml=$shtml. $hk;
        $shtml=$shtml. htmlspecialchars("</santitle></div></html>")."\n\n";
        $shtml=$shtml. htmlspecialchars('==<html><div id="sanskrita"><sanskrita>');
        $shtml=$shtml. $hk;
        $shtml=$shtml. htmlspecialchars('</sanskrita></div></html>');
        $shtml=$shtml. htmlspecialchars("&nbsp;''").htmlspecialchars($hkprevraiz).raizlink($hkraiz).htmlspecialchars("'' ");
        $shtml=$shtml. htmlspecialchars('<font color="#616E33">[ ');
        $shtml=$shtml. $hk;
        $shtml=$shtml. htmlspecialchars(' ]</font><!--<html><a href="/wiki/images/');
        $shtml=$shtml. substr($hk,0,1)."/".$hk.".wav";
        $shtml=$shtml. htmlspecialchars('"><img src="/wiki/images/audio.gif" width="19" height="18" border="0" /></a></html>-->==')."\n";
        $shtml=$shtml. "\n\n";
        $shtml=$shtml. htmlspecialchars('<multilang>')."\n";
        $shtml=$shtml. "\n\n";
        $shtml=$shtml. htmlspecialchars('@es|')."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** AQUI COMIENZA LA VERSION EN ESPANOL *** -->');
        $shtml=$shtml. ltrim($def)."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** AQUI TERMINA LA VERSION EN ESPANOL *** -->')."\n";
        $shtml=$shtml. htmlspecialchars('@en|')."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** ENGLISH VERSION STARTS HERE *** -->');
        $shtml=$shtml. ltrim($def)."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** ENGLISH VERSION ENDS HERE *** -->')."\n";
        $shtml=$shtml. htmlspecialchars('</multilang>')."\n";
    }
    else
    {
        ${dictorig.$pagedict}.=rtrim(str_replace("---> ","->",${'matriz'.($x)}[6]));
        $key[$page].=", ".keywordshk(${'matriz'.$x}[1]);
        $hkraiz=${'matriz'.$x}[5];
        $hkprevraiz=trim(${'matriz'.$x}[4]); // previo hasta raiz
        $hkprevraiz=str_replace("'","",$hkprevraiz);
        $palabras=split("&radic;",$hkraiz); // cortamos la raiz por si hay mas de una en la misma palabra
        $hkraiz1='';
        for($i=0;$palabras[$i];$i++)
        {
            if ($i>0)
                $hkraiz1.="&radic;";
            $hkraiz1.= raizlink($palabras[$i]);
        }
        $hk=${'matriz'.$x}[1];
        $def=str_replace('&','&amp;',${'matriz'.$x}[3]);
        $def=search_and_replace($def);
        $hksimbol=$hkprevraiz.$hkraiz1;
        if (strlen($hkraiz)<1)
            $hksimbol=simbols($hksimbol);        
        $shtml=$shtml. "\n\n";
        //echo htmlspecialchars("==''").rtrim(ltrim($hksimbol)).htmlspecialchars("'' ");
        $shtml=$shtml. htmlspecialchars("==''").htmlspecialchars($hksimbol).htmlspecialchars("'' ");
        $shtml=$shtml. htmlspecialchars('<font color="#616E33">[ ');
        $shtml=$shtml. $hk;
        $shtml=$shtml. htmlspecialchars(' ]</font><!--<html><a href="/wiki/images/');
        $shtml=$shtml. substr($hk,0,1)."/".$hk.".wav";
        $shtml=$shtml. htmlspecialchars('"><img src="/wiki/images/audio.gif" width="19" height="18" border="0" /></a></html>-->==')."\n";
        $shtml=$shtml. "\n\n";
        $shtml=$shtml. htmlspecialchars('<multilang>')."\n";
        $shtml=$shtml. "\n\n";
        $shtml=$shtml. htmlspecialchars('@es|')."\n";
        $shtml=$shtml. rtrim(ltrim(htmlspecialchars('<!-- *** AQUI COMIENZA LA VERSION EN ESPANOL *** -->')));
        $shtml=$shtml. ltrim($def)."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** AQUI TERMINA LA VERSION EN ESPANOL *** -->')."\n";
        $shtml=$shtml. htmlspecialchars('@en|')."\n";
        $shtml=$shtml. rtrim(ltrim(htmlspecialchars('<!-- *** ENGLISH VERSION STARTS HERE *** -->')));
        $shtml=$shtml. ltrim($def)."\n";
        $shtml=$shtml. htmlspecialchars('<!-- *** ENGLISH VERSION ENDS HERE *** -->')."\n";
        $shtml=$shtml. htmlspecialchars('</multilang>')."\n";
    }
    


}

$shtml.=htmlspecialchars('<!-- <mw page="'.($page*10).'"> -->');
$shtml.=htmlspecialchars('<!-- <keywords>'.$key[$page].'</keywords> -->');
$shtml.=htmlspecialchars('<!-- <link> </link> -->');
$shtml.=htmlspecialchars('<!-- <progress en="" es=""> -->');
$shtml.=htmlspecialchars('<!-- *** START DICT ORIGINAL ***'.${dictorig.$pagedict}.'*** END DICT ORIGINAL *** -->');
$shtml.='</text>
</revision>
</page>
</mediawiki>';
$shtml=str_replace("&gt; ","&gt;",$shtml);

$sfile="test.xml"; //ruta del archivo a generar
$fp=fopen($sfile,"w+");
fwrite($fp,$shtml);
fclose($fp);
echo "<a href='".$sfile."'>Haz click aqui para bajarlo</a>";
  #4 (permalink)  
Antiguo 28/04/2008, 09:08
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 10 meses
Puntos: 2135
Re: tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

Hola anibal_cdf,

Recuerda que PHP es un lenguaje interpretado, por lo que tiene otros usos, y para lo que requieres necesitas un lenguaje muy optimo en el manejo de memoria, por eso te recomiendo que mejor explores otras opciones para hacer tu parser, como C, o C++, que son lenguajes mas óptimos para la tarea que requieres.

Saludos.
  #5 (permalink)  
Antiguo 28/04/2008, 09:13
 
Fecha de Ingreso: marzo-2007
Mensajes: 180
Antigüedad: 17 años, 1 mes
Puntos: 0
Re: tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

gracias, pero no recuerdo mucho y para hacer tantas cosas como aca no se como hacerlo en c, y menos las funciones que convierten el codigo utf8 y html :(
  #6 (permalink)  
Antiguo 29/04/2008, 13:40
 
Fecha de Ingreso: marzo-2007
Mensajes: 180
Antigüedad: 17 años, 1 mes
Puntos: 0
Re: tengo un script con bucles y funciones que tarda mucho, como puedo hacer ?

bueno lo parti en 2, primero hacer la "separacion" que antes hacia a una matriz / array , y lo paso a una base de datos mysql.

luego con otro php levanto el mysql y lo voy pasando por las funciones y demas cambios.
Pero aca tambien se queda bastante tiempo.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:42.