The syntax for the timing function in Racket is confusing. If I want to check CPU cycles I should be able to wrap my entire code in (time codestuff) and it should produce that should it not? I get an error whenever I try to wrap it in (time).
lambda: no expression after a sequence of internal definitions in: lambda
What other choices do I have to check CPU usage for running my program in Scheme?
Unfortunately, time doesn't seem to work if the last form in the time body isn't an expression. Fortunately, (void) is an expression that is (relatively) free.1 You can just add it as the last expression in the body of your time giving you:
(time
.... your code here ....
(void))
So for example, the following code will give you a result like this:
> (time
(define x
(for/list ([i (in-range 1000000)])
i))
(void))
cpu time: 148 real time: 149 gc time: 124
1As with anything in CS and timing, whether or not void is going to matter here does depend. But for many cases a single call to void should be fine.
Related
Is it possible to call a procedure in Scheme after waiting a few seconds?
For example:
(define (facs)
(fac 3)
;wait 5 seconds
(fac 7))
There is no provision for a sleep procedure in Standard Scheme; you will need to rely on implementation-specific features.
If you are using Guile Scheme, you can use sleep to sleep for a number of seconds, or usleep to sleep for a number of microseconds:
(define (delayed-5s msg)
(display "Waiting 5s...")
(force-output)
(sleep 5)
(newline)
(display msg)
(newline))
Note that you should flush the output to be sure that messages are seen when you want them seen. Typically, (but not always) printing a newline will flush the output buffer, so you could move (newline) before (sleep 5) and reasonably expect that the display will work as expected; but it is better to flush the output explicitly to ensure that messages are flushed from the output buffer when you want them to be. In the above code, both force-output and sleep are Guile-specific procedures.
If you are using Chez Scheme, you can do this:
(define (delayed-5s msg)
(display "Waiting 5s...")
(flush-output-port (current-output-port))
(sleep (make-time 'time-duration 0 5))
(newline)
(display msg)
(newline))
In Chez Scheme, sleep takes a time object, and make-time takes three arguments, returning a time object. The first of those is a time-type argument, the second is the number of nanoseconds, and the third is the number of seconds. Again, you should flush the output buffer, and flush-output-port does that, but it needs an output-port, which the procedure current-output-port provides. In the above code, sleep and make-time are Chez-specific procedures, but flush-output-port and current-output-port are standard R6RS Scheme library procedures.
You can see that using the sleep facility provided by Chez Scheme is a little bit more involved than the one provided by Guile Scheme. Other implementations are likely to have similar provisions, but they are not required to.
Not in portable Scheme as far as I know. Many implementations will have ways of doing this, of course. For instance in Racket:
(define (sleepy s)
(values (current-seconds)
(begin
(sleep s)
(current-seconds))))
> (sleepy 2)
1612809817
1612809819
(Of course, current-seconds is also not part of standard Scheme.)
I have some kind of "main loop" using glut. I'd like to be able to measure how much time it takes to render a frame. The time used to render a frame might be used for other calculations. The use of the function time isn't adequate.
(time (procedure))
I found out that there is a function called current-time. I had to import some package to get it.
(define ct (current-time))
Which define ct as a time object. Unfortunately, I couldn't find any arithmetic packages for dates in scheme. I saw that in Racket there is something called current-inexact-milliseconds which is exactly what I'm looking for because it has nanoseconds.
Using the time object, there is a way to convert it to nanoseconds using
(time->nanoseconds ct)
This lets me do something like this
(let ((newTime (current-time)))
(block)
(print (- (time->nanoseconds newTime) (time->nanoseconds oldTime)))
(set! oldTime newTime))
Seems good enough for me except that for some reasons it was printing things like this
0
10000
0
0
10000
0
10000
I'm rendering things using opengl and I find it hard to believe that some rendering loop are taking 0 nanoseconds. And that each loop is quite stable enough to always take the same amount of nanoseconds.
After all, your results are not so surprising because we have to consider the limited timer resolution for each system. In fact, there are some limits that depend in general by the processor and by the OS processes. These are not able to count in an accurate manner than we expect, despite a quartz oscillator can reach and exceed a period of a nanosecond. You are also limited by the accuracy and resolution of the functions you used. I had a look at the documentation of Chicken scheme but there is nothing similar to (current-inexact-milliseconds) → real? of Racket.
After digging around, I came with the solution that I should write it in C and bind it to scheme using bindings.
(require-extension bind)
(bind-rename "getTime" "current-microseconds")
(bind* #<<EOF
uint64_t getTime();
#ifndef CHICKEN
#include <sys/time.h>
uint64_t getTime() {
struct timeval tim;
gettimeofday(&tim, NULL);
return 1000000 * tim.tv_sec + tim.tv_usec;
}
#endif
EOF
)
Unfortunately this solution isn't the best because it will be chicken-scheme only. It could be implemented as a library but a library to wrap only one function that doesn't exists on any other scheme doesn't make sense.
Since nanoseconds doens't actually make much sense after all, I got the microseconds instead.
Watch the trick here, define the function to get wrapped above and prevent the include to get parsed by bind. When the file will get loaded in Gcc, it will build with the include and function definition.
CHICKEN has current-milliseconds: http://api.call-cc.org/doc/library/current-milliseconds
(progn
(print 11)
(/ 1 0)
(print 22)
(/ 2 0)
(print 33))
When I press C-M-x on that expression, Emacs invokes debugger when it fails at (/ 1 0). When I press c for continue instead of q for quit, debugger still exits without executing (print 22) or (/ 2 0). The only difference here is that c exits with the message
progn: Arithmetic error
What is an example code where c and q make big difference and when should I type c rather than q?
The difference can be shown in any code that does not stop the execution, i.e. does not contain an error (for example, when called by debug).
The difference is easiest to see when you use debug-on-signal. With this setting, the debugger gets called when an error is signalled, even if that error is handled by an enclosing condition-case. In such a situation c will continue the normal execution (i.e. signal the error, which in turn causes the handler code to be run, which may then continue execution normally).
At first it seemed to me like a very obvious question,
but after trying to build an example, I actually had to look in the info.
So let me summarize what I've clarified for myself:
c in edebug is not the same as c in gdb.
This one just stops for one second at each breakpoint and eventually quits.
I don't see at the moment how it can be useful to anyone.
The equivalent is instead g: this one will continue until next breakpoint
and stop there.
Here's a code example:
(defun foo ()
(setq x (loop for i from 1 to 100
collecting (* i i)))
(setq y (nth 5 x))
(incf y))
(foo)
To edebug it:
Paste this code into *scratch*
Move point inside foo and C-u C-M-x (calls edebug-defun)
Move point to y in setq y and M-x edebug-set-breakpoint
Move point to the closing paren in (foo) and C-j
You're now in edebug. Here you could do step 3 with the shortcut b
instead of M-x ...
You'll find that proceeding with SPC is tedious, since it will
move though each statement of the loop each time.
But if you press g you'll skip past the whole loop, ending up
in the statement that you're supposedly interested in.
Another difference is with respect to recursive edit. For example, I could invoke query-replace and then enter recursive edit and then type (/ 1 0) and evaluate it to enter debugger. Now if I press q, we are back to top level and no longer running query-replace. But if I press c instead, I am still inside recursive edit.
Update another difference. While in debugger, c is bound to debugger-continue which is a wrapper around exit-recursive-edit
and q is bound to top-level. That means any difference known about exit-recursive-edit vs top-level applies. See Recursive Edit - Emacs Manual for difference.
Here's an example adapted from an example in Recursive Editing - Emacs Lisp Manual to test differences.
(defun simple-rec ()
(forward-word 1)
(message "111")
(debug)
(message "222")
(forward-word 1))
I have a Rscript that will load ggplot2 in its first line.
Though loading a library doesn't take much time, as this script may be executed in command line for millions of times so the speed is really important for me.
Is there a way to speed up this loading process?
Don't restart -- keep a persistent R session and just issue requests to it. Something like Rserve can provide this, and for example FastRWeb uses it very well -- with millsecond round-trips for chart generation.
As an addition to #MikeDunlavey's answer:
Actually, both library and require check whether the package is already loaded.
Here are some timings with microbenchmark I get:
> microbenchmark (`!` (exists ("qplot")),
`!` (existsFunction ('qplot')),
require ('ggplot2'),
library ('ggplot2'),
"package:ggplot2" %in% search ())
## results reordered with descending median:
Unit: microseconds
expr min lq median uq max
3 library("ggplot2") 259.720 262.8700 266.3405 271.7285 448.749
1 !existsFunction("qplot") 79.501 81.8770 83.7870 89.2965 114.182
5 require("ggplot2") 12.556 14.3755 15.5125 16.1325 33.526
4 "package:ggplot2" %in% search() 4.315 5.3225 6.0010 6.5475 9.201
2 !exists("qplot") 3.370 4.4250 5.0300 6.2375 12.165
For comparison, loading for the first time:
> system.time (library (ggplot2))
User System verstrichen
0.284 0.016 0.300
(these are seconds!)
In the end, as long as the factor 3 = 10 μs between require and "package:ggplot2" %in% search() isn't needed, I'd go with require, otherwise witht the %in% search ().
What Dirk said, plus you can use the exists function to conditionally load a library, as in
if ( ! exists( "some.function.defined.in.the.library" )){
library( the.library )
}
So if you put that in the script you can run the script more than once in the same R session.
Some sample, straight forward gtk2 within-main-loop
I'm currently trying to add code at key-press-event
If I make an error in the guy code, the gui thread will hang in the repl, I can still get the repl back but I didn't find a way to continue with gui development without restarting sbcl and reloading all the packages
(defun run ()
(within-main-loop
; match the controls that matter to vars
(let ((window (builder-get-object builder "window"))
;....
; on window close keep the gtk running. helps with debugging
(g-signal-connect search-field "key-press-event" (lambda (w) (declare (ignore w)) (format "~a" "danut")))
(g-signal-connect window "destroy" (lambda (w) (declare (ignore w)) (leave-gtk-main)))
(widget-show window)))))
The error I get when I run this function is :
debugger invoked on a SIMPLE-ERROR in thread #:
There is no applicable method for the generic function
#
when called with arguments
(NIL).
With enough work I can fix the error, but everytime I get something broken in the gui I can't make the backend thread to continue from where it hanged.
I tried all kinds of thread functions. list-all-treads will show:
(#<SB-THREAD:THREAD "cl-gtk2 main thread" RUNNING {CF48EF1}>
#<SB-THREAD:THREAD "initial thread" RUNNING {AA5F591}>)
This is all I tried until now:
(sb-thread:list-all-threads)
(sb-thread:interrupt-thread (first (sb-thread:list-all-threads)) #'leave-gtk-main)
(sb-thread:terminate-thread (first (sb-thread:list-all-threads)))
I just can't get it unstuck.
What's your normal workflow with cl-gtk2-gtk, how do you avoid this problem?
Use sb-thread:release-foreground to switch between threads waiting for input. See Threads in SBCL for an example session.