0

我正在学习一门新语言,正如我通常学习的那样,编写一个简单的任务,在字典中获取单词的字谜(定时和使用线程)。目前在用Groovy做程序,完成后又回到前段时间做的程序,对比时间和内存使用情况,结果发现Ruby程序吃光了所有资源。

事实上,线程不会同时启动,而是在开始时交替启动,有时会并行运行并消耗内存。这个事实在 Groovy、C++、Python 中是不同的。

你能让我知道我做错了什么吗?我无法确定错误在哪里。可以做些什么来避免这个问题?

PS:我不会说英语,如果我有拼写错误,请见谅。PS2:您可以尝试将关键字更改为“amor”而不是“neuralgica”,但使用“neuralgica”会出现 RAM 问题。

运行:ruby 2.0.0p0(2013-02-24 修订版 39474)[x86_64-linux]

红宝石代码:

require 'parallel'
require 'time'
require 'benchmark'

class Bot
  def initialize(nombre,diccL,intentos,termine,consola)
    @nombre,@diccL,@intentos,@termine,@consola=nombre,diccL,intentos,termine,consola
  end

  def buscarAlt()
    for intento in @intentos
      for palabra in @diccL
        if palabra[1]==intento
          @consola.synchronize{puts "\n============Anagrama-> " + @nombre+":"+palabra[1]}
          palabra = nil            
        end
        intento = nil
      end
    end
  end
end

class Master  

  def initialize(base)
    #number of bots(CPU cores)
    @K=4
    #Base is the keyword to find the anagrama
    @base=base

    #Loading Dict
    fDicc="alternativo"
    dicc=File.open(fDicc)
    @diccL=Hash.new
    i=0
    dicc.each do |linea|        
      @diccL[i]=linea.to_s.chomp
      i+=1
    end
    dicc.close

    @consola=Mutex.new


    @colaBots=Queue.new

    @permutaciones=@base.split("").permutation.map{|p| p.join("")}

  end

  def iniciar()



    time = Benchmark.realtime do

      inicio=Time.new
      puts "iniciar"

      fin=@K-1
      b=[]
      for i1 in 0..(fin)
        i=i1.to_i;
        b[i]= Bot.new("Bot" + i.to_s,@diccL,@permutaciones[i*(@permutaciones.length/@K)..(i+1)*(@permutaciones.length/@K)],@colaBots,@consola)
      end


      Parallel.map(b) do |bots| 
        bots.buscarAlt()
      end
      @consola.synchronize{puts "termino";fin =Time.new; puts fin.to_i - inicio.to_i }
    end
    puts (time*1000).to_s
  end  
end

常规代码:

@Grab(group='org.codehaus.gpars', module='gpars', version='1.1.0') 
import static groovyx.gpars.GParsPool.* 
class Consola {
    def synchronized void salida(mensaje) {
        println(mensaje)
    }
    static void main (args){
    }     
}

class Bot {
    def mi_diccionario
    def mi_id 
    def consola
    def palabra
    def permutaciones

    Bot (dict, id, out, word, perm){    
        this.mi_id = id
        this.mi_diccionario = dict
        this.consola = out
        this.palabra = word
        this.permutaciones = perm
    }

    def start() {        
        mi_diccionario.each{d->
            permutaciones.each{p->

                if ( p == d){
                    consola.salida("Anagrama encontrado ->" + d +" por bot:" + mi_id)
                }

            }
        }
    }

}

def benchmark = { closure ->  
    start = System.currentTimeMillis()  
    closure.call()  
    now = System.currentTimeMillis()  
    now - start  
}  


dir = "alternativo"
palabra_original = "neuralgica" //<- is the keyword to find the anagrama
palabras_permutadas = []
c = new Consola()
bots = []
//Number of bots (CPU cores)
nBots = 4

//Loading Dict
fileContents = new File(dir).getText('UTF-8')

palabras = fileContents.tokenize() 

palabra_original.split('')[1..palabra_original.length()].permutations().each {palabra_nueva-> palabras_permutadas.add(palabra_nueva.join())}

def duration = benchmark { 
    nBots.times{    
        bots[it] = new Bot(palabras,it,c,palabra_original,palabras_permutadas[it*(palabras_permutadas.size()/nBots)..((1+it)*(palabras_permutadas.size()/nBots)-1)])    
    }

    withPool {
        bots.eachParallel {        
            it.start()
        }
    }
}
println "execution took ${duration} ms"  

编辑:我发现了我的错误,我使用哈希来保存排列,我更改为字符串数组,然后解决。Ruby 比 Groovy 快。

4

0 回答 0