libmysql (c-api) slow compared to php-mysqli

530

I'm investigating why my C-test-program(libmysql) is almost twice as slow the same php-test(cli) program:

I'm creating a prepared-statement and inserting 10 records.

The php-cli-version(mysqlnd) is almost twice as fast as the C version using libmysql. I'm testing like so : time ./dbctest && timephp phptest.php

C-Version:

/*gcc dbctest.c  -o dbctest -lm -lmysqlclient -lz  -std=c99 */

#include <my_global.h>
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char my_str[16];
int my_str_length=0;
static void insert_records (MYSQL_STMT *stmt)
{
char            *stmt_str = "insert into bleach values (?)";
MYSQL_BIND      param[1];

//printf ("Inserting records...\n");
if (mysql_stmt_prepare (stmt, stmt_str, strlen (stmt_str)) != 0)
{
    fprintf(stderr,"\nCant prepare...");
    return;
}


memset ((void *) param, 0, sizeof (param)); /* zero the structures */

strcpy (my_str,"test");
my_str[5] = '\0';  
my_str_length = strlen (my_str);


param[0].buffer_type = MYSQL_TYPE_STRING;
param[0].buffer = (void *) my_str;
param[0].buffer_length = sizeof (my_str);
param[0].is_null = 0;


if (mysql_stmt_bind_param (stmt, param) != 0)
{
    fprintf(stderr,"\nCant bind..");
    return;
}



for (int i = 1; i < 10; i++)
{
    if (mysql_stmt_execute (stmt) != 0)
    {
        fprintf(stderr,"Error inserting row");
        return;
    }

}

}

int main (int argc, char *argv[])
{
MYSQL *conn;


conn = mysql_init(NULL);

if (conn == NULL) 
{
  printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
  exit(1);
}

if (mysql_real_connect(conn, "127.0.0.1", "root","password", "test_db", 0, NULL, 0) == NULL) 
{
    printf("Error %u: %s\n", mysql_errno(conn),     mysql_error(conn));
    exit(1);
}

MYSQL_STMT  *stmt;
stmt = mysql_stmt_init (conn); 
insert_records(stmt);
exit (0);
}

PHP-Version:

<?php
$mysqli = new mysqli("127.0.0.1", "root", "password",     "test_db");

$name = "TEST-PHP";
$stmt = $mysqli->prepare("insert into bleach values (?)");
$stmt->bind_param('s', $name);
for($i=0;$i< 10;$i++)
{
$stmt->execute();
}
$mysqli->close();
?>

People are also looking for solutions to the problem: php - I want to make a sum from 5 tables that have one column named "UP"

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.