File tree Expand file tree Collapse file tree 3 files changed +69
-0
lines changed Expand file tree Collapse file tree 3 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ const print = @import ("std" ).debug .print ;
2
+ const now = @import ("std" ).time .nanoTimestamp ;
3
+
4
+ fn fibonacci (index : u64 ) u64 {
5
+ if (index < 2 ) return index ;
6
+ return fibonacci (index - 1 ) + fibonacci (index - 2 );
7
+ }
8
+
9
+ fn run () void {
10
+ const number = 25 ;
11
+
12
+ // Run-time
13
+ const start1 = now ();
14
+ const res1 = fibonacci (number );
15
+ const end1 = now ();
16
+
17
+ // Compile-time
18
+ const start2 = now ();
19
+ const res2 = comptime fibonacci (number );
20
+ const end2 = now ();
21
+
22
+ print ("Run-time: {d} in {}ns\n " , .{ res1 , end1 - start1 });
23
+ print ("Compile-time: {d} in {}ns\n " , .{ res2 , end2 - start2 });
24
+ print ("\n " , .{});
25
+ }
26
+
27
+ pub fn main () void {
28
+ for (1.. 6) | _ | {
29
+ run ();
30
+ }
31
+ }
Original file line number Diff line number Diff line change
1
+ const print = @import ("std" ).debug .print ;
2
+
3
+ fn add (comptime T : type , a : T , b : T ) T {
4
+ return a + b ;
5
+ }
6
+
7
+ pub fn main () void {
8
+ const res1 = add (u8 , 5 , 10 );
9
+ const res2 = add (f32 , 100 , -10 );
10
+
11
+ print ("Result 1: {d}\n " , .{res1 });
12
+ print ("Result 2: {d}\n " , .{res2 });
13
+ }
Original file line number Diff line number Diff line change
1
+ # Comptime
2
+
3
+ ``` bash
4
+ $ zig run generics.zig
5
+ Result 1: 15
6
+ Result 2: 90
7
+ ```
8
+
9
+ ``` bash
10
+ $ zig run expression.zig
11
+ Run-time: 75025 in 1003800ns
12
+ Compile-time: 75025 in 0ns
13
+
14
+ Run-time: 75025 in 996000ns
15
+ Compile-time: 75025 in 0ns
16
+
17
+ Run-time: 75025 in 998600ns
18
+ Compile-time: 75025 in 0ns
19
+
20
+ Run-time: 75025 in 1000200ns
21
+ Compile-time: 75025 in 0ns
22
+
23
+ Run-time: 75025 in 1505500ns
24
+ Compile-time: 75025 in 0ns
25
+ ```
You can’t perform that action at this time.
0 commit comments