Brace Your Tcl Code

I show Python code for most examples here on the blog, but I am frequently reminded that a majority of OpenSees users write their scripts in Tcl. Because everything’s a string, there’s a lot of cool stuff you can do with Tcl expressions.

However, simple math expressions can take a relatively long time to execute. This can slow down your OpenSees analyses if you have large chunks of calculation-intense Tcl code, e.g., model generation, post-processing analysis results, or coding up the SDF equation of motion.

As described in this article, shared by an OpenSees Tcl power user, you can put braces around math expressions in Tcl in order to avoid “double substitution” of variables. The end result is the braces could speed up your Tcl code by a factor of almost 10! Here’s a simple demonstration of bracing math expressions in 1D mesh generation:

set L 120.0
set Nele 1000
set dX [expr {$L/$Nele}]

node 0 0.0 0.0

# SLOW
for {set i 1} {$i <= $Nele} {incr i} {
   node $i [expr $i*$dX] 0.0
}

# FAST
for {set i 1} {$i <= $Nele} {incr i} {
   node $i [expr {$i*$dX}] 0.0  ;# Notice the {}
}

The brace speedup only applies to native Tcl expressions and has no effect on the core OpenSees finite element calculations. No, your OpenSees analysis will not become 10 times faster.

Also, don’t go overboard putting entire OpenSees commands in braces: {node 1 0.0 0.0} will give you an invalid command error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.