If we want to run tasks in parallel, this can be tricky.
We want 5 files to run at the same time. If each file takes 2 seconds to run, then all of them should take 2 seconds if this is true, else it will take 10 seconds.
Method 1
The below example takes 10 seconds.
testfile.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php $companys=5; echo "Go "; while($i < $companys) { include('hitcounter.php'); $i++; } echo " Done"; ?> |
hitcounter.php (this one file takes 2 seconds to complete)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php sleep(2); // this makes the page wait 2 seconds $count_my_page = ("hitcounter.txt"); $hits = file($count_my_page); $hits[0] ++; $fp = fopen($count_my_page , "w"); fputs($fp , "$hits[0]"); fclose($fp); $hitme = $hits[0]; echo $hitme; ?> |
Conclusion: – each file is run in series therefore this example takes 10 seconds to complete…
(Not the answer I was looking for)
I then wrote a script that writes to a database the time in seconds and milliseconds and run this in the same way. The results show that it takes two seconds for each file. The correct result should be all have the same second at least!
I changed hitcounter.php to the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php sleep(2); include('myconn.inc'); $milliseconds = round(microtime(true) * 1000); $mydate =date("H:i:s - "); //latest hour? $mydate=$mydate.$milliseconds; $query = "INSERT INTO sortabletable (time) VALUES ('$mydate')"; mysql_query($query) or die(mysql_error()); ?> <h5 style="margin:10px;">Method 2 (batch files)</h5> Add this to a file called myfile.bat and save to the desktop. C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\testfolder\hitcounter.php" |
It runs the file and adds to the database the time it ran….great!
Lets do two of them…
1 2 3 4 |
C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\testfolder\hitcounter.php" C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\testfolder\hitcounter.php" |
Ok this ran but there was still a two second gap between inserts….
Lets add a magic word….. START
1 2 3 4 |
START C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\testfolder\hitcounter.php" START C:\wamp\bin\php\php5.5.12\php.exe -f "C:\wamp\www\testfolder\hitcounter.php" |
Now we have the files being run with only a very very small time difference ie 30-40 milliseconds….
Conclusion
Therefore if we wish to run files at the same time use a bat file with start….this does not run then wait for a file to come back to it….