Advertisement
mython

PHP/Python/Java comparison

Apr 5th, 2020
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. PHP (linear search):
  2. 500'000 numbers
  3. 100 all_numbers
  4. execution time: 0.645s
  5.  
  6. Python (linear search):
  7. 500'000 numbers
  8. 100 all_numbers
  9. execution time: 0.737s
  10.  
  11. Python (with set):
  12. 500'000 numbers
  13. 100 all_numbers
  14. execution time: 0.022s
  15.  
  16. Java (with HashSet):
  17. 50'000'000 numbers (100x PHP)
  18. 100 all_numbers
  19. execution time: 0.308s
  20.  
  21.  
  22. Codice:
  23. [PHP]
  24. <?php
  25. function fn() {
  26. $numbers = range(0, 500 * 1000);
  27. $all_numbers = range(0, 100);
  28. for ($i = 0; $i < 100; $i++) {
  29. $all_numbers[$i] = rand(0, 1000);
  30. }
  31. $cnt = 0;
  32. $t0 = microtime(true);
  33. foreach ($numbers as $n) {
  34. if (in_array($n, $all_numbers)) {
  35. $cnt = $cnt + 1;
  36. }
  37. }
  38. $t1 = microtime(true);
  39. print_r($t1 - $t0);
  40. echo "<br>";
  41. print_r($cnt);
  42. }
  43.  
  44. fn()
  45. ?>
  46.  
  47.  
  48. [Python]
  49. import random
  50. import time
  51.  
  52. def test():
  53. random.seed()
  54. numbers = range(500 * 1000)
  55. all_numbers = [random.randint(0, 1000) for _ in range(100)]
  56. all_numbers = set(all_numbers)
  57. cnt = 0
  58. t0 = time.time()
  59. for n in numbers:
  60. if n in all_numbers:
  61. cnt += 1
  62. t1 = time.time()
  63. print("%0.6f - %d" % (t1 - t0, cnt))
  64.  
  65. test()
  66.  
  67.  
  68. [Java]
  69. import java.util.HashSet;
  70. import java.util.Random;
  71.  
  72. class Prova {
  73. static void test() {
  74. int[] numbers = new int[50 * 1000 * 1000];
  75. int i;
  76. int cnt = 0;
  77. HashSet<Integer> all_numbers = new HashSet<Integer>();
  78.  
  79. for (i = 0; i < numbers.length; i++) {
  80. numbers[i] = i;
  81. }
  82.  
  83. Random rnd = new Random();
  84. for (i = 0; i < 100; i++) {
  85. all_numbers.add(rnd.nextInt());
  86. }
  87.  
  88. long t0 = System.currentTimeMillis();
  89. for (int n: numbers) {
  90. if (all_numbers.contains(n)) {
  91. cnt++;
  92. }
  93. }
  94. long t1 = System.currentTimeMillis();
  95. System.out.println(t1 - t0 + " - " + cnt);
  96. }
  97.  
  98. public static void main(String[] args) {
  99. test();
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement