Last active
June 10, 2023 12:52
-
-
Save sebnyberg/b18eab9463c3697127629ca0ee829245 to your computer and use it in GitHub Desktop.
Roman To Integer Benchmarks
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
| package tmp | |
| import ( | |
| "math/rand" | |
| "testing" | |
| ) | |
| func randRoman() string { | |
| letters := "MDCCLXXVII" | |
| bm := 1 + rand.Intn((1<<(len(letters)))-1) | |
| var res []byte | |
| for i := range letters { | |
| if bm&(1<<i) > 0 { | |
| res = append(res, letters[i]) | |
| } | |
| } | |
| return string(res) | |
| } | |
| var res int | |
| func a(x int) int { | |
| return x | |
| } | |
| func BenchmarkRoman(b *testing.B) { | |
| const n = 1e5 | |
| nums := make([]string, n) | |
| for i := range nums { | |
| nums[i] = randRoman() | |
| } | |
| b.Run("map", func(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| res = romanToIntMap(nums[i%n]) | |
| a(res) | |
| } | |
| }) | |
| b.Run("array", func(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| res = romanToIntArr(nums[i%n]) | |
| a(res) | |
| } | |
| }) | |
| b.Run("func", func(b *testing.B) { | |
| for i := 0; i < b.N; i++ { | |
| res = romanToIntFunc(nums[i%n]) | |
| a(res) | |
| } | |
| }) | |
| } | |
| func romanToIntMap(s string) int { | |
| var romanMap = map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} | |
| var result = romanMap[s[len(s)-1]] | |
| for i := len(s) - 2; i >= 0; i-- { | |
| if romanMap[s[i]] < romanMap[s[i+1]] { | |
| result -= romanMap[s[i]] | |
| } else { | |
| result += romanMap[s[i]] | |
| } | |
| } | |
| return result | |
| } | |
| func romanToIntArr(s string) int { | |
| var romanMap = [...]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} | |
| var result = romanMap[s[len(s)-1]] | |
| for i := len(s) - 2; i >= 0; i-- { | |
| if romanMap[s[i]] < romanMap[s[i+1]] { | |
| result -= romanMap[s[i]] | |
| } else { | |
| result += romanMap[s[i]] | |
| } | |
| } | |
| return result | |
| } | |
| func romanToIntFunc(s string) int { | |
| var result = getVal(s[len(s)-1]) | |
| for i := len(s) - 2; i >= 0; i-- { | |
| if getVal(s[i]) < getVal(s[i+1]) { | |
| result -= getVal(s[i]) | |
| } else { | |
| result += getVal(s[i]) | |
| } | |
| } | |
| return result | |
| } | |
| func getVal(s byte) int { | |
| switch s { | |
| case 'I': | |
| return 1 | |
| case 'V': | |
| return 5 | |
| case 'X': | |
| return 10 | |
| case 'L': | |
| return 50 | |
| case 'C': | |
| return 100 | |
| case 'D': | |
| return 500 | |
| case 'M': | |
| return 1000 | |
| default: | |
| return 0 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.