Can I do this code faster? On my computer for the file in the 3 million lines 
it runs 14 seconds. When using memfiles - one second faster. While text editors 
produce the same operation is much faster: AkelPad - 7 seconds, Notepad ++ - 
2-3 seconds.

PS: Attempts to be played with a size of the buffer (bufferSize parameter) 
didn't give any effect.
    
    
    import nre,os,times
    
    proc main()=
      var
        fIn,fOut:File
        ARGS = commandLineParams()
        line:TaintedString = ""
        fileTmp = joinPath(getEnv("TEMP"), "tmp.tmp")
        pattern,fileSource,fileDest:string
        countRepl,countLine = 0
        bufferSize = 1024 * 10
      
      if (ARGS.len < 3 ):
        echo "repl - utility to replace the lines in the file"
        echo "Copyright(C): Gary Galler, 2016.  All rights reserved\n"
        echo "Error: Not enough arguments\n"
        echo "Example: repl source.txt \"search string\" \"line for 
replacement\" dest.txt"
        echo "Example: repl source.txt \"search string\" \"line for 
replacement\""
        quit()
      
      fileSource = expandFilename(ARGS[0])
      if not open(fIn,ARGS[0],  fmRead, bufferSize): echo "Error: Could not 
open file:", fileSource;quit()
      if not open(fOut,fileTmp,fmWrite, bufferSize): echo "Error: Could not 
open file:", fileTmp;   quit()
      
      pattern = ARGS[1]
      while(fIn.readLine(line)):
        countLine+=1
        if line.match(pattern.re).isSome:
          countRepl+=1
          fOut.writeLine(line.replace(pattern.re, ARGS[2]))
        else: fOut.writeLine(line)
      
      fOut.close()
      fIn.close()
      
      if (ARGS.len > 3 ):
        fileDest = expandFilename(ARGS[3])
        removeFile(fileDest);   moveFile(fileTmp, fileDest)
      else:
        removeFile(fileSource); moveFile(fileTmp, fileSource)
      echo "Produced: line " & $countLine & ", replacements " & $countRepl
    # end main
    
    var startTime = epochTime()
    main()
    var endTime = epochTime()
    echo "Time: ",endTime - startTime," seconds"
    

Reply via email to