Search code examples
erlangmnesia

erlang for loop for queries


I have this function:

show_employee_table() ->
    do(qlc:q([B || B <- mnesia:table(employee)])).

What it does is that it goes to a table called employee and prints the contents to the user.

Concept: I want to make another function say called show(times) -->, this function will take a table name and the number of times to call the show_table function.

If I input (employee,100), I want to have a for loop that runs 100 times, the idea is to measure the time taken to run the loop. In java I would do something like this:

Time t = time.now();
for ( I=0; I<N; I++){
show_employee_table() ->
    do(qlc:q([B || B <- mnesia:table(employee)])).
}

Time t2 = time.now();

timetaken = t2 - t1;

That's how I want to do it, but in erlang. I just don't know the syntax in erlang and I would appreciate it if someone can help me.


Solution

  • For time measurement, use: timer:tc/1, timer:tc/2, timer:tc/3. So we will have a recursive function called loop which may be doing anything you want. Then we would measure the time it takes to loop by applying

    {TimeTaken,Result} = timer:tc(?MODULE,loop,Args).
    

    Args must be a list of arguments to the function say, a table and a number, like this

    measureLoopTime()->
       Args = [employee,100],
       {TimeTaken,_Result} = timer:tc(?MODULE,loop,Args),
       TimeTaken.
    
    loop(_,0) -> done;
    loop(Table,Number)->
      %%% do something ....
      loop(Table, Number - 1).
    

    That's the correct erlang implementation of your java code. Follow the link to the timing function to see in which units the time is returned.