Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PHP (linear search):
- 500'000 numbers
- 100 all_numbers
- execution time: 0.645s
- Python (linear search):
- 500'000 numbers
- 100 all_numbers
- execution time: 0.737s
- Python (with set):
- 500'000 numbers
- 100 all_numbers
- execution time: 0.022s
- Java (with HashSet):
- 50'000'000 numbers (100x PHP)
- 100 all_numbers
- execution time: 0.308s
- Codice:
- [PHP]
- <?php
- function fn() {
- $numbers = range(0, 500 * 1000);
- $all_numbers = range(0, 100);
- for ($i = 0; $i < 100; $i++) {
- $all_numbers[$i] = rand(0, 1000);
- }
- $cnt = 0;
- $t0 = microtime(true);
- foreach ($numbers as $n) {
- if (in_array($n, $all_numbers)) {
- $cnt = $cnt + 1;
- }
- }
- $t1 = microtime(true);
- print_r($t1 - $t0);
- echo "<br>";
- print_r($cnt);
- }
- fn()
- ?>
- [Python]
- import random
- import time
- def test():
- random.seed()
- numbers = range(500 * 1000)
- all_numbers = [random.randint(0, 1000) for _ in range(100)]
- all_numbers = set(all_numbers)
- cnt = 0
- t0 = time.time()
- for n in numbers:
- if n in all_numbers:
- cnt += 1
- t1 = time.time()
- print("%0.6f - %d" % (t1 - t0, cnt))
- test()
- [Java]
- import java.util.HashSet;
- import java.util.Random;
- class Prova {
- static void test() {
- int[] numbers = new int[50 * 1000 * 1000];
- int i;
- int cnt = 0;
- HashSet<Integer> all_numbers = new HashSet<Integer>();
- for (i = 0; i < numbers.length; i++) {
- numbers[i] = i;
- }
- Random rnd = new Random();
- for (i = 0; i < 100; i++) {
- all_numbers.add(rnd.nextInt());
- }
- long t0 = System.currentTimeMillis();
- for (int n: numbers) {
- if (all_numbers.contains(n)) {
- cnt++;
- }
- }
- long t1 = System.currentTimeMillis();
- System.out.println(t1 - t0 + " - " + cnt);
- }
- public static void main(String[] args) {
- test();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement