Function frequency: Difference between revisions
(→{{header|Go}}: fixed output) |
m (Added comment for "Output") |
||
Line 91: | Line 91: | ||
(for X (head 10 (flip (by cdr sort Freq))) |
(for X (head 10 (flip (by cdr sort Freq))) |
||
(tab (-7 4) (car X) (cdr X)) ) )</lang> |
(tab (-7 4) (car X) (cdr X)) ) )</lang> |
||
Output, for the system in debug mode plus the above code: |
|||
Output: |
|||
<pre>quote 310 |
<pre>quote 310 |
||
car 236 |
car 236 |
Revision as of 09:11, 3 November 2011
Display - for a program or runtime environment (whatever suites the style of your language) - the top ten most frequently occurring functions.
This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by the programmer.
Go
Only crude approximation is currently easy in Go. The following parses source code, looks for function call syntax (an expression followed by an argument list) and prints the expression. <lang go>package main
import (
"fmt" "go/ast" "go/parser" "go/token" "io/ioutil" "os" "sort"
)
func main() {
if len(os.Args) != 2 { fmt.Println("usage ff <go source filename>") return } src, err := ioutil.ReadFile(os.Args[1]) if err != nil { fmt.Println(err) return } fs := token.NewFileSet() a, err := parser.ParseFile(fs, os.Args[1], src, 0) if err != nil { fmt.Println(err) return } f := fs.File(a.Pos()) m := make(map[string]int) ast.Inspect(a, func(n ast.Node) bool { if ce, ok := n.(*ast.CallExpr); ok { start := f.Offset(ce.Pos()) end := f.Offset(ce.Lparen) m[string(src[start:end])]++ } return true }) cs := make(calls, 0, len(m)) for k, v := range m { cs = append(cs, &call{k, v}) } sort.Sort(cs) for i, c := range cs { fmt.Printf("%-20s %4d\n", c.expr, c.count) if i == 9 { break } }
}
type call struct {
expr string count int
} type calls []*call
func (c calls) Len() int { return len(c) } func (c calls) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c calls) Less(i, j int) bool { return c[i].count > c[j].count }</lang> Output, when run on source code above:
len 3 fmt.Println 3 f.Offset 2 make 2 fmt.Printf 1 ioutil.ReadFile 1 a.Pos 1 string 1 token.NewFileSet 1 append 1
PicoLisp
<lang PicoLisp>(let Freq NIL
(for "L" (filter pair (extract getd (all))) (for "F" (filter atom (fish '((X) (or (circ? X) (getd X))) "L" ) ) (accu 'Freq "F" 1) ) ) (for X (head 10 (flip (by cdr sort Freq))) (tab (-7 4) (car X) (cdr X)) ) )</lang>
Output, for the system in debug mode plus the above code:
quote 310 car 236 cdr 181 setq 148 let 136 if 127 and 124 cons 110 cadr 80 or 76