时间序列元编程

Time-Series Coding

Posted by Zeusro on February 6, 2026
👈🏻 Select language

由于时间序列库原始的论文http://github.com/zeusro/data已经丢失了,我只能按照有限的回忆一点点拼凑起时间序列那部分的内容。

只有经过时间的实践,才能验证程序的正确性。因此我提出时间序列元编程模型。这是一种对现实世界提出建模的新程序范式,是编程语言无关的设计哲学。

在此基础上引入时间序列复杂度:在满足传统时间/空间复杂度前提下,用二维图(t 与内存利用率等)乃至三维图(加入 CPU/GPU 负载)刻画算法实际耗时与资源利用。

时间序列

时间序列:按时间顺序排列、记录同一对象状态随时间变化的一组数据。 时间序列只有Watch作为唯一API。Watch可以按照顺序分化为ReadWrite接口。

时间序列对象

时间序列对象,时间必须是第一成员,并且在初始化函数中体现。 基于时间而生成的数据都是时序数据。

1
2
3
4
5
6
7
8
type DeadMonkey struct {
	Birth       time.Time
	GoldenStaff []NLine //金箍棒 参数化线段(Parametric Segment)
	m           int     //消费者规模
	n           int     //算法规模
	ZeroPoints  []model.Point
	cost        time.Duration
}

时间序列函数

时间序列函数,时间必须是第一成员。返回参数第一成员必须是时间序列对象。 传入的时间与传出的时间,表示函数的时间上下界。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// NewDeadMonkey
// m 作战对象
// n 唯一资源数/算法规模
func NewDeadMonkey(birth time.Time, m, n int) *DeadMonkey {
	dead := DeadMonkey{
		Birth: birth,
		m:     m,
		n:     n,
	}
	zeroPoints := make([]model.Point, m)
	p0 := model.RandonPoint()
	zeroPoints[0] = p0
	for i := 1; i < m; i++ {
		p1 := model.RandonPoint()
		//只要不跟前面的点重复就行,全局重复也忽略了
		for p1.Compare(zeroPoints[i-1]) {
			p1 = model.RandonPoint()
		}
		zeroPoints[i] = p1
	}
	dead.ZeroPoints = zeroPoints
	return &dead
}

// SleepAndReturnNewTime 接收一个时间参数,随机 sleep 一段时间后返回最新时间
func SleepAndReturnNewTime(inputTime time.Time) time.Time {
    // 设置随机种子
    rand.Seed(time.Now().UnixNano())

    // 生成随机的 sleep 时间,范围为 1 到 5 秒
    sleepDuration := time.Duration(rand.Intn(5)+1) * time.Second

    // Sleep 随机时间
    time.Sleep(sleepDuration)

    // 返回当前时间
    return time.Now()
}

时间序列距离

使用时间+其他条件的复合判断(比如在4维球面中,可以只使用距离作为换算;也可以使用时间+Haversine公式换算)。

时间序列日志

打印内容必须是“时间+内容”的格式。

时间序列复杂度

时间序列复杂度(Time Series Complexity):在满足时间复杂度以及空间复杂度的前置性论述下,算法执行的实际时间以及内存资源的利用效率。

时间序列复杂度是一个二维图表。X轴是t,Y轴是(used - buff/cache) / total

Y轴可以按照实际需要,使用其他的标准,比如CPU/GPU的整体利用率。

单位时间序列复杂度是一个三维图表。 不过三维图表过于抽象,可以降维成2个2维图表。或者合并Y轴,变成一个二维图表的两条曲线。

单位CPU时间序列复杂度是一个三维图表。 X轴是t, Y轴是(used - buff/cache) / total, Z轴是cpu_load1。

单位GPU时间序列复杂度是一个三维图表。 X轴是t, Y轴是(used - buff/cache) / total, Z轴是gpu_utilization。

时间序列复杂度需要对程序进行可观测性分析。

时间序列空间

由时间序列组成的2维以上空间。

在OOOShttps://github.com/zeusro/system中,我将会尽可能地使用这种编程范式。

比如

The original paper for the time-series library http://github.com/zeusro/data has been lost, so I can only piece together the time-series part from limited memory.

Only through practice over time can the correctness of a program be verified. I therefore propose the time-series meta-programming model—a new programming paradigm for modeling the real world, a design philosophy independent of programming language.

On this basis, time-series complexity is introduced: under the premise of satisfying traditional time and space complexity, two-dimensional plots (e.g. t vs. memory utilization) and even three-dimensional plots (adding CPU/GPU load) are used to characterize the actual execution time and resource utilization of algorithms.

Time Series

Time series: A set of data arranged in chronological order that records how the state of the same object changes over time.
A time series has only Watch as its sole API. Watch can be split in order into Read and Write interfaces.

Time-Series Objects

For a time-series object, time must be the first member and must be reflected in the initialization function.
Any data generated based on time is time-series data.

1
2
3
4
5
6
7
8
type DeadMonkey struct {
	Birth       time.Time
	GoldenStaff []NLine // Golden Cudgel – Parametric Segment
	m           int     // consumer scale
	n           int     // algorithm scale
	ZeroPoints  []model.Point
	cost        time.Duration
}

Time-Series Functions

For a time-series function, time must be the first parameter. The first member of the return value must be a time-series object.
The input time and output time represent the lower and upper time bounds of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// NewDeadMonkey
// m combat objects
// n unique resource count / algorithm scale
func NewDeadMonkey(birth time.Time, m, n int) *DeadMonkey {
	dead := DeadMonkey{
		Birth: birth,
		m:     m,
		n:     n,
	}
	zeroPoints := make([]model.Point, m)
	p0 := model.RandonPoint()
	zeroPoints[0] = p0
	for i := 1; i < m; i++ {
		p1 := model.RandonPoint()
		// As long as it doesn't duplicate the previous point; global duplicates are ignored
		for p1.Compare(zeroPoints[i-1]) {
			p1 = model.RandonPoint()
		}
		zeroPoints[i] = p1
	}
	dead.ZeroPoints = zeroPoints
	return &dead
}

// SleepAndReturnNewTime accepts a time argument, sleeps randomly, then returns the latest time
func SleepAndReturnNewTime(inputTime time.Time) time.Time {
    // Set random seed
    rand.Seed(time.Now().UnixNano())

    // Generate random sleep duration, 1 to 5 seconds
    sleepDuration := time.Duration(rand.Intn(5)+1) * time.Second

    // Sleep for random duration
    time.Sleep(sleepDuration)

    // Return current time
    return time.Now()
}

Time-Series Distance

Use composite criteria of time plus other conditions (e.g. on a 4-dimensional sphere, distance alone may be used for conversion; or time plus the Haversine formula).

Time-Series Logging

Log output must follow the format “time + content”.

Time-Series Complexity

Time-series complexity: Under the prerequisite of time complexity and space complexity, the actual execution time of an algorithm and the utilization efficiency of memory resources.

Time-series complexity is represented as a two-dimensional plot. The X-axis is t, the Y-axis is (used - buff/cache) / total.

The Y-axis can use other metrics as needed, such as overall CPU/GPU utilization.

Unit time-series complexity is a three-dimensional plot. Three-dimensional plots are rather abstract; they can be reduced to two 2D plots, or the Y-axes can be merged into two curves on a single 2D plot.

Unit CPU time-series complexity is a three-dimensional plot: X-axis t, Y-axis (used - buff/cache) / total, Z-axis cpu_load1.

Unit GPU time-series complexity is a three-dimensional plot: X-axis t, Y-axis (used - buff/cache) / total, Z-axis gpu_utilization.

Time-series complexity requires observability analysis of the program.

Time-Series Space

A space of two or more dimensions composed of time series.

In OOOS https://github.com/zeusro/system, I will use this programming paradigm as much as possible.

For example:

Оригинальная статья по библиотеке временных рядов http://github.com/zeusro/data утрачена, поэтому я могу лишь по обрывочным воспоминаниям восстановить часть, касающуюся временных рядов.

Только практика во времени способна проверить корректность программы. Поэтому я предлагаю модель метапрограммирования временных рядов — новую программную парадигму для моделирования реального мира, философию проектирования, не привязанную к языку программирования.

На этой основе вводится сложность временных рядов: при соблюдении традиционной временной и пространственной сложности двумерные графики (например, t и утилизация памяти) и даже трёхмерные (с учётом нагрузки CPU/GPU) описывают фактическое время выполнения алгоритма и использование ресурсов.

Временной ряд

Временной ряд: упорядоченный по времени набор данных, фиксирующий изменение состояния одного и того же объекта во времени.
У временного ряда единственный API — Watch. Watch по порядку разбивается на интерфейсы Read и Write.

Объект временного ряда

У объекта временного ряда время должно быть первым полем и отражаться в функции инициализации.
Любые данные, порождённые на основе времени, являются данными временного ряда.

1
2
3
4
5
6
7
8
type DeadMonkey struct {
	Birth       time.Time
	GoldenStaff []NLine // Золотая дубинка – параметрический отрезок
	m           int     // масштаб потребителей
	n           int     // масштаб алгоритма
	ZeroPoints  []model.Point
	cost        time.Duration
}

Функция временного ряда

У функции временного ряда первым аргументом должно быть время. Первое поле возвращаемого значения должно быть объектом временного ряда.
Входное и выходное время задают нижнюю и верхнюю временные границы функции.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// NewDeadMonkey
// m боевые объекты
// n число уникальных ресурсов / масштаб алгоритма
func NewDeadMonkey(birth time.Time, m, n int) *DeadMonkey {
	dead := DeadMonkey{
		Birth: birth,
		m:     m,
		n:     n,
	}
	zeroPoints := make([]model.Point, m)
	p0 := model.RandonPoint()
	zeroPoints[0] = p0
	for i := 1; i < m; i++ {
		p1 := model.RandonPoint()
		// Достаточно не совпадать с предыдущей точкой; глобальные повторы игнорируются
		for p1.Compare(zeroPoints[i-1]) {
			p1 = model.RandonPoint()
		}
		zeroPoints[i] = p1
	}
	dead.ZeroPoints = zeroPoints
	return &dead
}

// SleepAndReturnNewTime принимает аргумент времени, случайно «засыпает», затем возвращает актуальное время
func SleepAndReturnNewTime(inputTime time.Time) time.Time {
    // Установить зерно случайности
    rand.Seed(time.Now().UnixNano())

    // Случайная длительность сна от 1 до 5 секунд
    sleepDuration := time.Duration(rand.Intn(5)+1) * time.Second

    // Сон на случайное время
    time.Sleep(sleepDuration)

    // Вернуть текущее время
    return time.Now()
}

Расстояние во временном ряде

Используется составной критерий: время плюс другие условия (например, на 4-мерной сфере можно опираться только на расстояние или на время и формулу Haversine).

Логирование временного ряда

Содержимое вывода должно быть в формате «время + содержание».

Сложность временного ряда

Сложность временного ряда (Time Series Complexity): при заданных временной и пространственной сложности — фактическое время выполнения алгоритма и эффективность использования памяти.

Сложность временного ряда изображается двумерным графиком. По оси X — t, по оси Y — (used - buff/cache) / total.

По оси Y при необходимости можно использовать другие метрики, например общую загрузку CPU/GPU.

Единичная сложность временного ряда — трёхмерный график. Трёхмерный график слишком абстрактен; его можно свести к двум двумерным или объединить оси Y в две кривые на одном двумерном графике.

Единичная CPU-сложность временного ряда — трёхмерный график: ось X — t, ось Y — (used - buff/cache) / total, ось Z — cpu_load1.

Единичная GPU-сложность временного ряда — трёхмерный график: ось X — t, ось Y — (used - buff/cache) / total, ось Z — gpu_utilization.

Для сложности временного ряда требуется анализ наблюдаемости программы.

Пространство временных рядов

Пространство размерности два и выше, состоящее из временных рядов.

В OOOS https://github.com/zeusro/system я буду по возможности применять эту программную парадигму.

Например: