Last active
May 3, 2017 12:48
-
-
Save romanitalian/7d611b0d1648e92b603c to your computer and use it in GitHub Desktop.
Time execution: foreach vs array_map (parse csv)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Parse csv using: array_map | |
* @param $path_to_csv_file | |
* @param string $delimiter | |
* @return array | |
*/ | |
// function m_str_getcsv($path_to_csv_file, $delimiter = ";") { | |
// return array_map( | |
// function ($item) use ($delimiter) { | |
// return explode($delimiter, trim($item)); | |
// }, | |
// file($path_to_csv_file) | |
// ); | |
// } | |
function m_str_getcsv($path_to_csv_file, $delimiter = ";", $line_break = "\n") { | |
$rows = explode($line_break, @file_get_contents($path_to_csv_file)); | |
if (empty(trim(end($rows)))) { | |
array_pop($rows); | |
} | |
return array_map(function ($item) use ($delimiter) {return explode($delimiter, $item);}, $rows); | |
} | |
/** | |
* Parse csv using: foreach | |
* @param $path | |
* @return array | |
*/ | |
function m2_str_getcsv($path) { | |
$out = array(); | |
$s = trim(file_get_contents($path)); | |
$rows = explode("\n", $s); | |
if(!empty($rows)) { | |
foreach($rows as $row) { | |
$out[] = explode(";", $row); | |
} | |
} | |
return $out; | |
} | |
function str_getcsv_origin($path, $delimiter = ";", $enclosure = "\n", $escape = "\\") { | |
return str_getcsv(@file_get_contents(path), $delimiter, $enclosure, $escape) | |
} | |
/** | |
* @param $func | |
* @param $count_execution_func | |
* @return string | |
*/ | |
function run_test($func, $count_execution_func = 100) { | |
$t = microtime(true); | |
$times = array(); | |
$path = 'otchet.csv'; | |
for($i = 0; $i < $count_execution_func; ++$i) { | |
$func($path); | |
$times[] = microtime(true) - $t; | |
} | |
return $times; | |
} | |
//////////////////////////////////////// test: //////////////////// | |
$t[] = run_test('m_str_getcsv'); | |
$t[] = run_test('m2_str_getcsv'); | |
$t[] = run_test('str_getcsv_origin'); | |
echo "<pre>\n\n".str_replace('.', ',', implode("\n", $t[0]))."</pre>"; | |
echo "<pre>\n\n".str_replace('.', ',', implode("\n", $t[1]))."</pre>"; | |
echo "<pre>\n\n".str_replace('.', ',', implode("\n", $t[2]))."</pre>"; | |
// average time execution: foreach vs array_map | |
echo (array_sum($t[0])/count($t[0])) / (array_sum($t[1])/count($t[1])); // 2.9423094638524 | |
echo (array_sum($t[0])/count($t[0])) / (array_sum($t[2])/count($t[2])); // ? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment