1

I'm trying to improve the performance of a Tcl script. It is a simple random sample with replacement algorithm. I know it's better to do this in a more numerically orientated language, but the platform I'm in uses Tcl.

Here is the code I generated, but it's relatively slow. It takes about 1 second per loop for an input list of about 100,000 double precision values. I have to process this loop hundreds of times.

proc pSampleWithReplace {list samplesize} {
set v_val {}
for {set j 0} {$j < $samplesize} {incr j} {
        lappend v_val [lindex $list [expr round(rand() * [expr [llength $list] -1])]]
    }
return $v_val
}

Is there something I can change in the expression that can improve the performance?

1 Answer 1

2

You're recalculating the list length every time. Also, brace your expressions.

proc pSampleWithReplace {list samplesize} {
    set v_val [list]   ;# you know it's a list, so create it as a list
    set lmax [expr {[llength $list] - 1}]
    for {set j 0} {$j < $samplesize} {incr j} {
        lappend v_val [lindex $list [expr {round(rand() * $lmax)}]]
    }
    return $v_val
}
1
  • Thanks. Bracing the expression makes a huge difference. That improved the performance by almost 2x alone.
    – Jonjilla
    Feb 11, 2015 at 21:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .