Last active
July 25, 2020 17:08
-
-
Save spytheman/18ec982aa485ecb2a20b8a70c0ab4894 to your computer and use it in GitHub Desktop.
a small demo of vlang vlib/rand, vlib/benchmark, and rand.uuid_v4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import os.cmdline | |
| import rand | |
| import benchmark | |
| // | |
| // Example run with: | |
| // ./v -prod -cc tcc run rand_uuid4_compare.v -repetitions 1000000 | |
| // ./v -prod -cc gcc-9 run rand_uuid4_compare.v -repetitions 1000000 | |
| // ./v -prod -cc clang-10 run rand_uuid4_compare.v -repetitions 1000000 | |
| // | |
| fn main() { | |
| repetitions := cmdline.option(os.args, '-repetitions', '10_000_000').int() | |
| println('repetitions: $repetitions') | |
| mut bench := benchmark.start() | |
| mut x := '' | |
| for _ in 0 .. repetitions { | |
| x = rand.uuid_v4() | |
| } | |
| bench.measure('$x rand.uuid_v4') | |
| for _ in 0 .. repetitions { | |
| x = uuid_v4q() | |
| } | |
| bench.measure('$x rand.uuid_v4q') | |
| } | |
| fn uuid_v4q() string { | |
| mut buf := malloc(37) | |
| alpha_displacement := if true { byte(39) } else { byte(7) } // if true use a-f else A-F | |
| mut i_buf := 0 | |
| for i_buf < 36 { | |
| mut x := rand.u64() | |
| x &= 0x0F0F_0F0F_0F0F_0F0F | |
| x += 0x3030_3030_3030_3030 | |
| mut c := 0 | |
| for c < 8 && i_buf < 36 { | |
| mut d := byte(x) | |
| x = x >> 8 | |
| if i_buf == 19 { | |
| // d = ((d & 0x3) | 0x8) + 0x30 | |
| // more compact version | |
| d = (d & 0x3) + 0x38 | |
| } | |
| d = if d > 0x39 { d + alpha_displacement } else { d } | |
| unsafe { | |
| buf[i_buf] = d | |
| } | |
| i_buf++ | |
| c++ | |
| } | |
| } | |
| unsafe { | |
| buf[8] = `-` | |
| buf[13] = `-` | |
| buf[14] = `4` | |
| buf[18] = `-` | |
| buf[23] = `-` | |
| buf[36] = 0 | |
| } | |
| return string(buf, 36) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment