I would like to have less than 1ms delay between two rows in TCL script. I'm interesting in 1us, or even several nanoseconds. Is there any option to do that in TCL only? Is there any command like "after" that able to do so?
Asked
Active
Viewed 308 times
2 Answers
2
Tcl's own built-in timers are all using delays with a granularity of one millisecond (or more on Windows in some build configurations).
If you want shorter delays, you'll need to add a bit of C code (necessarily platform-specific). Here's an example for Linux:
#include <tcl.h>
#include <string.h>
#include <time.h>
static int NanosleepCmd(ClientData ignored, Tcl_Interp *interp,
int objc, Tcl_Obj *const objv[]) {
struct timespec sleepTime;
int result;
// Parse the argument
memset(&sleepTime, 0 , sizeof(sleepTime));
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "nanoseconds");
}
if (Tcl_GetLongFromObj(interp, objv[1], &sleepTime.tv_nsec) != TCL_OK) {
return TCL_ERROR;
}
if (sleepTime.tv_nsec < 0 || sleepTime.tv_nsec > 999999999) {
Tcl_AppendResult(interp, "nanoseconds must be in range 0..999999999", NULL);
return TCL_ERROR;
}
// Do the sleep
result = nanosleep(&sleepTime);
// It's a system call; you should ALWAYS check for errors afterwards!
if (result != 0) {
Tcl_SetObjResult(interp, Tcl_ObjPrintf(
"failed to nanosleep: %s", Tcl_PosixError(interp)));
return TCL_ERROR;
}
return TCL_OK;
}
int Nanosleep_Init(Tcl_Interp *interp) {
Tcl_CreateObjCommand(interp, "nanosleep", NanosleepCmd, NULL, NULL);
return TCL_OK;
}
Build that as dynamic library (e.g., called nanosleep.so
) and then do:
load nanosleep.so

Donal Fellows
- 133,037
- 18
- 149
- 215
-
It's also possible to busy-loop for that, but it's _really_ not a great plan. – Donal Fellows Sep 19 '21 at 11:09
-
See also https://stackoverflow.com/questions/7827062/is-there-a-windows-equivalent-of-nanosleep for what to do on Windows (where it's _messy,_ alas). – Donal Fellows Sep 19 '21 at 11:10
0
There is no such possibility available in plain Tcl.
You didn't indicate why you need it. One reason could be to communicate with hardware. This is why the piio library provides a piio usleep
command.
Note that due to the overhead of calling the command, the actual delay will always be longer than requested. But this will ensure that events don't follow each other more quickly than the specified amount of microseconds.

Schelte Bron
- 4,113
- 1
- 7
- 13