自研小工具-1-汇总

一、period_run

1. 简介

usage: period_run <run_us> <sleep_us>

静态编译的高精度周期运行和休眠程序。运行和休眠时长可控制。

i=0; while true; do if [ "$i" -lt 20 ]; then i=$((i + 1)); else i=0; fi; sleep 0.01; done & //单次运行至少1ms以上,主要是在创建sleep进程。


2. 用处

(1) 辅助火焰图验证小线程调度相关分量(_raw_spin_unlock)占比多大合理。

 

3. 源码

(1) period_run.cpp

/*
 * 工具: period_run <run_us> <sleep_us> 
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define NSEC_PER_SEC   1000000000L
#define NSEC_PER_US    1000L

/* 模拟需要运行 100us 的工作任务 */
void do_busy_work(long run_us) {
    long target_nsec = run_us * NSEC_PER_US;
    long elapsed_nsec = 0;
    struct timespec start, now;

    clock_gettime(CLOCK_MONOTONIC, &start);

    /* 自旋等待直到满 100 微秒(微秒级的高精度运行通常需要自旋等待) */
    do {
        clock_gettime(CLOCK_MONOTONIC, &now);
        elapsed_nsec = (now.tv_sec - start.tv_sec) * NSEC_PER_SEC + (now.tv_nsec - start.tv_nsec);
    } while (elapsed_nsec < target_nsec);
}

int main(int argc, char *argv[]) {
    long increment_nsec, run_time_us, sleep_time_us;
    struct timespec next_period;

    if (argc != 3) {
        printf("usage: period_run <run_us> <sleep_us> \n");
        return -1;
    }
    
    run_time_us = atol(argv[1]);
    sleep_time_us = atol(argv[2]);
    printf("run_time_us=%ld, sleep_time_us=%ld\n", run_time_us, sleep_time_us);

    /* 获取当前时间作为基准 */
    clock_gettime(CLOCK_MONOTONIC, &next_period);

    while (1) {
        /* 1. 执行任务(耗时约 100us) */
        do_busy_work(run_time_us);

        /* 
         * 2. 计算下一个周期的绝对触发时间
         * 一个完整的周期 = 运行时间(100us) + 休眠时间(8ms) = 8100us
         */
        increment_nsec = (sleep_time_us + run_time_us) * NSEC_PER_US;
        next_period.tv_nsec += increment_nsec;
        if (next_period.tv_nsec >= NSEC_PER_SEC) {
            next_period.tv_sec += next_period.tv_nsec / NSEC_PER_SEC;
            next_period.tv_nsec %= NSEC_PER_SEC;
        }

        /*
         * 3. 使用绝对时间休眠,防止时间漂移
         * TIMER_ABSTIME 参数确保即使系统被中断,休眠也会准确在指定的绝对时间唤醒
         */
        clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next_period, NULL);
    }

    return 0;
}

(2) Android.bp

cc_binary {
    name: "period_run",
    srcs: [
        "period_run.cpp",
    ],
    defaults: ["cc_period_run_defaults"],
}

cc_defaults {
    name: "cc_period_run_defaults",
    cflags: [
        "-Wall",
        "-Werror",
        "-Wno-unused-function",
        "-Wno-unused-parameter",
        "-Wno-unused-variable",
    ],
    static_libs: [
        "libc",
        "libcutils",
        "liblog",
   ],
   static_executable: true,
}

 

posted on 2026-09-30 15:51  Hello-World3  阅读(7)  评论(0)    收藏  举报

导航