関数がcalc_sum()
あり、その実行時間を測定したいとします。info_callback()
メッセージを出力して実行時間を計算するコールバック関数があります。パラメーターとして void ポインターを使用します。にキャストvoid*
して実行時間の開始/終了を取得し、差を計算したいのですが、関数内からその要素にアクセスできるようstruct timeval *
に配列にポインタを渡す方法がわかりません。何を試しても、セグメンテーション違反が発生します...struct timeval *
info_callback()
ポインターを機能させるには、どのようにポインターを渡してキャストする必要がありますか?
編集: Andy Schweigが提案したように、コードのエラーを修正しました
#include <stdio.h>
#include <sys/time.h>
void calc_sum(int a, int b)
{
int k = a + b;
printf("sum = %d\n", k);
}
void info_callback(const char *msg, void *client_data)
{
struct timeval *t = (struct timeval *) client_data;
double time = (t[1].tv_sec - t[0].tv_sec) * 1000.0; // !!!SEGMENTATION FAULT!!!
time += (t[1].tv_usec - t[0].tv_usec) / 1000.0; //
printf("[TIME] %s: %f, ms", msg, time);
}
int main(int argc, char *argv[])
{
struct timeval t1, t2;
gettimeofday(&t1, NULL);
calc_sum(2, 3);
gettimeofday(&t2, NULL);
struct timeval * tr = (struct timeval*) malloc(2 * sizeof(struct timeval));
tr[0] = t1;
tr[1] = t2;
double time = (tr[1].tv_sec - tr[0].tv_sec) * 1000.0; // sec to ms
time += (tr[1].tv_usec - tr[0].tv_usec) / 1000.0; // us to ms
printf("time = %f, ms\n", time);
info_callback("Execution time", tr);
free(tr);
}