find_prime.pyΒΆ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""
This example demonstrates how Python code can be run in a browser, which
is faster than CPython in many cases. We run the exact same code to find
the n-th prime on both Python and JS and measure the performance.
"""

from time import perf_counter

from flexx import app, event


def find_prime(n):
    primes = []

    def isprime(x):
        if x <= 1:
            return False
        elif x == 2:
            return True
        for i in range(2, x//2+1):
            if x % i == 0:
                return False
        return True

    t0 = perf_counter()
    i = 0
    while len(primes) < n:
        i += 1
        if isprime(i):
            primes.append(i)
    t1 = perf_counter()
    print(i, 'found in ', t1-t0, 'seconds')


class PrimeFinder(app.PyComponent):

    def init(self):
        self.js = PrimeFinderJs()

    @event.action
    def find_prime_py(self, n):
        find_prime(n)

    @event.action
    def find_prime_js(self, n):
        self.js.find_prime_js(n)


class PrimeFinderJs(app.JsComponent):

    @event.action
    def find_prime_js(self, n):
        find_prime(n)


if __name__ == '__main__':

    # Create app instance
    finder = app.launch(PrimeFinder, 'app or chrome-app')

    finder.find_prime_py(2000)  # 0.6-0.7 s
    finder.find_prime_js(2000)  # 0.1-0.2 s

    app.run()