Skip to content

Commit f7fd079

Browse files
Qian WenjieQian Wenjie
authored andcommitted
CORES==0 disable parallel
1 parent 533293c commit f7fd079

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

README.md

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ the cache mechanism of pure function call with the same parameters. By adding
2020
parameter "*debug=True*", it is easy to show the evaluation process step by step.
2121

2222
>>> from lazy import Lazy
23+
>>> lazy_int = Lazy(int, debug=True)
2324
>>> def fib(n):
24-
... return Lazy(int, debug=True)(n) if n <= 1 else fib(n-1) + fib(n-2)
25+
... return lazy_int(n) if n <= 1 else fib(n-1) + fib(n-2)
2526
...
2627
>>> a = fib(10)
2728
>>> a
@@ -84,7 +85,7 @@ example shows how the implicit parallel works by using decorator *lazy*.
8485
s.eval()
8586
print(s)
8687

87-
$ time python3 1.py
88+
$ time python3 test_parallel.py
8889
((f1()*f2())+(f3()*f4()))
8990
Enter f1
9091
Enter f2
@@ -98,5 +99,26 @@ example shows how the implicit parallel works by using decorator *lazy*.
9899

99100
real 0m5.173s
100101
user 0m0.111s
101-
sys 0m0.049s
102+
sys 0m0.049s
103+
104+
You can easily change the number of CPU cores in parallel computing by adding
105+
*Lazy.set_cores(num)*. You can completely disable parallel by *Lazy.set_cores(0)*.
106+
107+
$ time python3 test_parallel_with_zero_cores.py
108+
((f1()*f2())+(f3()*f4()))
109+
Enter f2
110+
Leave f2
111+
Enter f1
112+
Leave f1
113+
Enter f3
114+
Leave f3
115+
Enter f4
116+
Leave f4
117+
14
118+
119+
real 0m20.085s
120+
user 0m0.055s
121+
sys 0m0.016s
122+
123+
102124

lazy/lazy.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,13 +133,16 @@ def startjob(self):
133133
Lazy.JOBS.discard(self)
134134
if self.remote:
135135
Lazy.ACTIVE += 1
136-
self.POOL.apply_async(self.operator, args, callback = self.finish)
136+
if Lazy.POOL:
137+
Lazy.POOL.apply_async(self.operator, args, callback = self.finish)
138+
else:
139+
self.finish(self.operator(*args))
137140
else:
138141
self.finish(self.operator(*args))
139142
def eval(self):
140143
if self.value is not None:
141144
return self.value
142-
if Lazy.POOL is None:
145+
if Lazy.POOL is None and Lazy.CORES > 0:
143146
Lazy.POOL = Pool(Lazy.CORES)
144147
self.remote = False
145148
self.setdepth(0)
@@ -152,7 +155,7 @@ def eval(self):
152155
def schedule(cls):
153156
while cls.JOBS:
154157
next = max(list(cls.JOBS), key=lambda x:x.depth)
155-
if next.depth == -1 or next.remote and cls.ACTIVE >= cls.CORES:
158+
if next.depth == -1 or next.remote and cls.CORES > 0 and cls.ACTIVE >= cls.CORES:
156159
break
157160
next.startjob()
158161

0 commit comments

Comments
 (0)