在LoadRunner中处理Unix毫秒时间戳:添加4天偏移的问题
解决LoadRunner中毫秒时间戳的日期偏移计算问题
问题根源
你遇到的数值溢出问题,核心原因是误用了atoi()函数——它仅支持32位int范围的数值转换(最大值为2147483647),但13位的毫秒级Unix时间戳(如1686784563045)远超出这个范围,导致转换后数值失真。
解决方案
使用支持64位整数的字符串转数值函数(如atoll()),将时间戳转换为long long类型进行运算,彻底避免溢出。具体步骤:
- 用
lr_save_timestamp()捕获当前毫秒时间戳 - 将参数值转换为
long long类型 - 加上4天对应的毫秒数(4×24×60×60×1000 = 345600000)
- 将计算结果存回LoadRunner参数供后续请求使用
修正后的代码示例
timestamp() { long long int fromTimestamp, toTimestamp; const long long FOUR_DAYS_IN_MS = 4LL * 24 * 60 * 60 * 1000; // 固定4天的毫秒数 // 捕获当前毫秒时间戳 lr_save_timestamp("time", LAST); lr_output_message("原始时间戳 -> %s", lr_eval_string("{time}")); // 转换为64位整数(用atoll处理大数值) fromTimestamp = atoll(lr_eval_string("{time}")); lr_output_message("转换后的起始时间戳 -> %lld", fromTimestamp); // 计算4天后的结束时间戳 toTimestamp = fromTimestamp + FOUR_DAYS_IN_MS; lr_output_message("4天后的时间戳 -> %lld", toTimestamp); // 保存为LoadRunner参数,供后续接口调用 lr_save_string(lr_eval_string("{time}"), "startDate"); lr_save_sprintf("endDate", "%lld", toTimestamp); return 0; }
代码关键说明
atoll():专门用于将字符串转换为long long(64位整数),完全适配13位毫秒时间戳的数值范围FOUR_DAYS_IN_MS:用4LL强制以64位整数计算,避免中间运算出现溢出lr_save_sprintf():将计算后的64位整数格式化为字符串,保存为参数后可直接在后续请求中通过{endDate}引用
预期执行输出
Starting iteration 1. Starting action timestamp. timestamp.c(8): Notify: Saving Parameter "time = 1686784563045". timestamp.c(9): 原始时间戳 -> 1686784563045 timestamp.c(13): 转换后的起始时间戳 -> 1686784563045 timestamp.c(16): 4天后的时间戳 -> 1687130163045 timestamp.c(19): Notify: Saving Parameter "startDate = 1686784563045". timestamp.c(20): Notify: Saving Parameter "endDate = 1687130163045". Ending action timestamp. Ending iteration 1.
内容的提问来源于stack exchange,提问作者Nike
相关产品推荐
相关产品推荐

