OILS / mycpp / examples / length.py View on Github | oilshell.org

109 lines, 65 significant
1#!/usr/bin/env python2
2"""
3length.py
4"""
5from __future__ import print_function
6
7import os
8from mycpp.mylib import log
9from mycpp import mylib
10
11from typing import Optional
12
13
14def TestMaybeStrEquals():
15 # type: () -> None
16
17 a = 'foo'
18 b = 'bar'
19
20 y = 'foo' # type: Optional[str]
21 n = None # type: Optional[str]
22
23 log('a == b -> %d', a == b)
24 log('a != b -> %d', a != b)
25
26 log('a == y -> %d', a == y)
27 log('a != y -> %d', a != y)
28
29 log('a == n -> %d', a == n)
30 log('a != n -> %d', a != n)
31
32
33def run_tests():
34 # type: () -> None
35 mystr = 'abcd'
36 log("len(mystr) = %d", len(mystr))
37 log("mystr[1] = %s", mystr[1])
38 log("mystr[1:] = %s", mystr[1:])
39 log("mystr[1:3] = %s", mystr[1:3])
40 log("mystr[:-2] = %s", mystr[:-2])
41
42 for c in mystr:
43 if c == 'b':
44 continue
45 log('c = %s', c)
46 if c == 'c':
47 break
48
49 log("")
50
51 # NOTE: Not implementing mylist[:n] or mylist[:-1] (negative) until I see
52 # usages.
53 mylist = ['w', 'x', 'y', 'z']
54 log("len(mylist) = %d", len(mylist))
55 log("mylist[1] = %s", mylist[1])
56
57 # can't print lists directly
58 log("len(mylist[1:]) = %d", len(mylist[1:]))
59
60 for c in mylist:
61 if c == 'x':
62 continue
63 log('c = %s', c)
64 if c == 'y':
65 break
66
67 # to test nullptr. Python correctly infers this as 'str'
68 c2 = None # type: Optional[str]
69 for c2 in mystr:
70 if c2 != 'a': # test != operator
71 log('%s != a', c2)
72
73 log('')
74
75 TestMaybeStrEquals()
76
77
78def run_benchmarks():
79 # type: () -> None
80 n = 1000000
81
82 mystr = 'abcd'
83 mylist = ['w', 'x', 'y', 'z']
84
85 result = 0
86 i = 0
87 while i < n:
88 # C++ has a big advantage here
89 #result += len(mystr)
90 #result += len(mylist)
91
92 # C++ shows no real advantage here
93 result += len(mystr[1:])
94 result += len(mylist[1:])
95
96 i += 1
97
98 mylib.MaybeCollect()
99
100 log('result = %d', result)
101 log('iterations = %d', n)
102
103
104if __name__ == '__main__':
105 if os.getenv('BENCHMARK'):
106 log('Benchmarking...')
107 run_benchmarks()
108 else:
109 run_tests()