0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

c: 一定間隔の処理

Last updated at Posted at 2025-06-30

こちらと同じことを c で行いました。
Python3: 一定間隔の処理

プログラム

signal01.c
// ---------------------------------------------------------------
/*
	signal01.c

						Jun/30/2025
*/
// ---------------------------------------------------------------
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <stdint.h>

// 高精度時間計測用
#ifdef __MACH__
#include <mach/mach_time.h>
#else
#include <time.h>
#endif

static double start_time;

// ---------------------------------------------------------------
// 高精度時間取得関数
double get_current_time() {
#ifdef __MACH__  // macOS
	static mach_timebase_info_data_t timebase;
	if (timebase.denom == 0) {
		mach_timebase_info(&timebase);
	}
	return (double)mach_absolute_time() * timebase.numer / timebase.denom / 1e9;
#else  // Linux
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
#endif
}

// ---------------------------------------------------------------
// シグナルハンドラ
void scheduler(int sig) {
	double end_time = get_current_time();
	double time_diff = end_time - start_time;
	printf("%.15f\n", time_diff);
}

// ---------------------------------------------------------------
int main() {
	struct itimerval timer;

fprintf(stderr,"*** start ***\n");
	
	// 高精度開始時間を記録
	start_time = get_current_time();

	// シグナルハンドラ設定
	signal(SIGALRM, scheduler);

	// タイマー設定 (1秒間隔)
	timer.it_value.tv_sec = 0;
	timer.it_value.tv_usec = 250 * 1000;
	timer.it_interval.tv_sec = 0;
	timer.it_interval.tv_usec = 250 * 1000;

	// タイマー開始
	setitimer(ITIMER_REAL, &timer, NULL);

	// プログラムを実行し続ける
	while(1) {
		pause();
	}

	return 0;
}

// ---------------------------------------------------------------
Makefile
signal01: signal01.c
	gcc -o signal01 signal01.c
clean:
	rm -f signal01

コンパイル

make

実行結果

$ ./signal01 
*** start ***
0.250418912999521
0.500412539999161
0.750079572999311
1.000398118998419
1.250394679998863
1.500404860998970
1.750399118000132
2.000395888999265
2.250052305998906
2.500403330999688
2.750392629999624
3.000112466999781

確認した環境

Ubuntu 25.04

$ uname -a
Linux shimizu 6.14.0-22-generic #22-Ubuntu SMP PREEMPT_DYNAMIC Wed May 21 15:01:51 UTC 2025 x86_64 x86_64 x86_64 GNU/Linux

RaspberryPi

$ uname -a
Linux dahlia 6.12.25+rpt-rpi-v8 #1 SMP PREEMPT Debian 1:6.12.25-1+rpt1 (2025-04-30) aarch64 GNU/Linux
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?