K
K
Konstantin Savinov2015-02-04 18:48:02
PHP
Konstantin Savinov, 2015-02-04 18:48:02

How to optimize the parsing of comments in a VKontakte group?

Good afternoon!
There is a script that runs on cron and checks if there are new comments on the group wall for the last N posts. Now the script looks like this:

$public = ""; // Домен группы
$publicid = ""; // ID группы
$howmuch = 15; // Количество постов
$log = file_get_contents("log2.txt"); // Файл с ID комментариев

// Забираем посты по API ВК
$getWall = file_get_contents('https://api.vk.com/method/wall.get?v=5.27&domain='.$public.'&count='.$howmuch);
$getWall = json_decode($getWall);
$getWall = $getWall->response->items;

for ($i = 0; $i < $howmuch; $i++) {
  // Спим 0.3 секунды
  usleep(333333);

  // Забираем комменты к N посту по API ВК
  $getComm = file_get_contents('https://api.vk.com/method/wall.getComments?v=5.27&owner_id='.$publicid.'&post_id='.$getWall[$i]->id.'&count=100');
  $getComm = json_decode($getComm);
  $getComm = $getComm->response->items;

  for ($b = 0; $b < count($getComm); $b++) {
  // Если ID коммента уже есть в файле log2.txt, то ничего не делаем
  if (preg_match('/'.$getComm[$b]->id.'/', $log)) {
  }
  // Если такого ID в логе нет, то выводим коммент на странице
  else {
  echo '<span style="font-family:Arial;font-size:14px;">'.$getComm[$b]->text.'<br><a href="http://vk.com/wall'.$publicid.'_'.$getWall[$i]->id.'?reply='.$getComm[$b]->id.'">link</a></span><p>&nbsp;</p>';
  // И попутно записываем его ID в лог
  $file=fopen("log2.txt", "a");
  fwrite ($file, $getComm[$b]->id."\n");
  fclose($file);
  }
  }
}

Now everything works fine, but with these settings, the script runs for about 10 seconds.
Question: is it possible to somehow optimize it so that it works at least a little faster?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
IceJOKER, 2015-02-04
@IceJOKER

15 records at 0.3s (your usleep(333333)--- 333333ms - is that really 0.3 seconds? O_O )= 4.5
At least you can write these lines:

if (preg_match('/'.$getComm[$b]->id.'/', $log)) {
  }

more competently
and what for ID to store in a file.
$file=fopen("log2.txt", "a");
  fwrite ($file, $getComm[$b]->id."\n");
  fclose($file);

^^^
are you lazy? when all this can be done in one line
offset - use this parameter wisely and you will save yourself from getting extra comments, which will increase performance

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question